2.6 Shallow & Deep Copying
If We Never Write Our Own
If our data members do not have explicit copy
constructors (and their data members do not have explicit copy
constructors, and …) then the compiler-provided copy
constructor amounts to a bit-by-bit copy.
Shallow vs Deep Copy
Copy operations are distinguished by how they
treat pointers:
- In a shallow copy, all pointers are
copied.
- Leads to shared data on the heap.
- In a deep copy, objects pointed to are
copied, then the new pointer set to the address of the copied
object.
- Copied objects keep exclusive access to the
things they point to.
Shallow copy is wrong when...
- Your ADT has pointers among its data members,
and
- You don’t want to share the objects being
pointed to.
Compiler-generated copy constructors are wrong
when...
- Your ADT has pointers among its data members,
and
- You don’t want to share the objects being
pointed to.
