Skip to content

Deep copies for classes owning heap memory

Question

Why does a C++ class that allocates memory itself need hand-written copy construction and copy assignment?

Short answer

Because the defaults copy the pointer, not the data. Two objects then share one buffer: changing one alters the other, and both destructors free it (a double delete); default assignment also leaks the target's old buffer. Implement deep copies (copy-and-swap handles self-assignment and exception safety) following the rule of three/five, or better, hold the memory in a std::vector or smart pointer.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.16, p.226; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question