Re: when can pass by value be dangerous?
From: Howard (alicebt_at_hotmail.com)
Date: 03/08/05
- Next message: nospam: "Re: Small C++ exercise"
- Previous message: Daniel Haude: "Re: Advantages of C++ over C - request for information"
- In reply to: ceo: "when can pass by value be dangerous?"
- Next in thread: Andrey Tarasevich: "Re: when can pass by value be dangerous?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 08 Mar 2005 16:39:13 GMT
"ceo" <ceo.msft@gmail.com> wrote in message
news:1110298924.760376.239580@f14g2000cwb.googlegroups.com...
> Hi there,
>
> I'm reffering to a text that says following:
>
> "To summarize: When a copy of an object is generated because it passed
> to a function, the object's constructor function is not called.
> However, when the copy of the object inside the function is destroyed,
> its destructor is called.
>
> By default, when a copy of an object is made, a bitwise copy occurs.
> This means that the new object is an exact duplicate of the original.
> The fact that an exact copy is made can, at time, be a source of
> trouble. Even though objects are passed to functions by means of the
> normal call-by-value parameter passing mechanism, which, in theory,
> protects and insulates the calling argument. For example, if an object
> used as an argument allocates memory and frees that memory when it is
> destroyed, then its local copy inside the function will free the same
> memory when its destructor is called. This will leave the original
> object damaged and effectively useless."
>
> Could someone give me an example that will damage the original object?
>
> Thanks,
> Ceo
>
Suppose the object has a pointer inside it to another, dynamically allocated
sub-object. What happens then? When the object is passed by value and gets
copied, its internal pointer simply gets copied. But now, both objects have
pointers to the SAME sub-object instead of to separate copies of that
sub-object.
This is exactly what the copy constructor is for! If your object contains
pointers to dynamic memory, then you're likely going to need a copy
constructor (as well as an assignment operator and a destructor), because
the default (compiler-generated) ones will not suffice. (Google for the
"Rule of Three".)
-Howard
- Next message: nospam: "Re: Small C++ exercise"
- Previous message: Daniel Haude: "Re: Advantages of C++ over C - request for information"
- In reply to: ceo: "when can pass by value be dangerous?"
- Next in thread: Andrey Tarasevich: "Re: when can pass by value be dangerous?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|