![]() |
|
#1
|
|||
|
|||
deep copy and shallow copyHi ,
can anybody tell me the diff between deep copy and shallow copy. |
|||
|
#2
|
||||
|
||||
Re: deep copy and shallow copyI think (and someone please correct me if I'm wrong) that a shallow copy is when you create another reference to the same object.
CPP / C++ / C Code:
Now a deep copy (again, someone please correct me if necessary) is when you reallocate the memory for an object, generally with a copy constructor. CPP / C++ / C Code:
Here o2 is a deep copy of o1, because the memory is reallocated for the object. Even though they contain the same information, o1 and o2 are different objects. Gamer_2k4 |
|
#3
|
|||
|
|||
Re: deep copy and shallow copyNice explanation Gamer. There's another twist to this, one that's more dangerous in code. Suppose the class testObject contains a c-style string, in other words a dynamically allocated char array.
CPP / C++ / C Code:
This program crashes as it terminates because of a double delete. Since no copy constructor is provided in testObject, the compiler creates a default one, which simply copies over the values of all the member variables. This is a shallow copy. The problem is, with the shallow copy o1.m_str == o2.m_str; in other words the two pointers point to the same place in memory. Then when they go out of scope, a destructor is called and deletes that memory. Then -- whoops -- another destructor is called and deletes the same memory. Crash. The solution to this is to provide a copy constructor for testObject. (To be safe, there's also an assignment overload operator that does the same thing. See explanation below.) CPP / C++ / C Code:
|
|
#4
|
||||
|
||||
Re: deep copy and shallow copythats right
The proper definition as i know it is Shallow copy Just copies the member data nothing else (big problems if there is allocated memory)(the default copy constructor uses shallow copies) Deep copy Copies everything and if there is allocated memory allocates itself some memory for the data (insted of just copying the pointer data (ends up with 2 pointers to same place as ubergeek said)) __________________
Forgive my english (I am english i just can't spell) PS:What do you think of the avatar, i drew parts myself |
Recent GIDBlog
Install Adobe Flash - Without Administrator Rights by LocalTech
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The