What is the difference between a shallow copy and a deep copy? Give a scenario where a shallow copy causes a crash.
Last updated
A shallow copy duplicates the object's members bit-for-bit, so pointer members in both objects point to the same underlying resource; a deep copy allocates and copies the pointed-to resource too, giving each object its own independent copy. Shallow copies of owning pointers cause double-free crashes.
Shallow copy:
Member-wise copy: the default compiler-generated copy constructor and copy assignment.
Fine for value-only members; dangerous when a member owns heap memory.
Deep copy: Custom copy constructor/assignment allocates new storage and copies the contents, so the objects don't share state.
Crash scenario:
A class holds a raw
int*to heap memory it deletes in its destructor.Shallow-copy it: two objects hold the same pointer. When both destruct, the memory is
deleted twice (double free): undefined behavior, typically a crash.
Rule of three / five: If you write a destructor, you likely need a copy constructor and copy assignment too (and move versions in modern C++). Better: hold a
unique_ptrorvectorso copy semantics are correct by default.