Shallow copy:
Some members of the copy may refer to the same objects as the original:
class X { private: int i; int *pi; public: X() : pi(new int) { } X(const X& copy)
Here, the pi member of the original and copied object X will point to the same int .
Deep copy:
All members of the original are cloned (recursively, if necessary). No shared objects:
class X { private: int i; int *pi; public: X() : pi(new int) { } X(const X& copy)
Here, the pi member of the original and copied object X will point to different int objects, but both of them have the same value.
The default copy constructor (which is automatically provided if you do not provide one yourself) creates only small copies.
Correction: A few comments below correctly pointed out that it is wrong to say that the default copy constructor always always executes a shallow copy (or a deep copy, for that matter). Regardless of whether the designer of the type copy creates a shallow copy or a deep copy, or something in between , depends on the combination of behavior of each copy member; a member type copy constructor can be made to do whatever it wants in the end.
This section 12.8, clause 8 of the 1998 C ++ standard, talks about the above code examples:
An implicit copy constructor for class X performs a copy of its subobjects. [...] Each subobject is copied into a method corresponding to its type: [...] [I] f the subobject has a scalar type, a built-in assignment operator b.
stakx Apr 17 '10 at 8:50 2010-04-17 08:50
source share