Topic 5 of 27 · Intermediate
Copy Control: Rule of 3/5/0
Copy constructor, assignment, deep vs shallow copy.
Concept
If a class manages a resource (raw memory, file handle), the default copy just copies the pointer — a shallow copy that leads to double frees.
Rule of three: if you need a destructor, copy constructor or copy assignment, you probably need all three. Rule of five adds move constructor and move assignment.
Rule of zero: use std::string, std::vector and smart pointers so you need none of them.
Code (C++20)
#include <cstring>
class Buffer {
char* data_;
std::size_t n_;
public:
explicit Buffer(std::size_t n) : data_(new char[n]{}), n_(n) {}
~Buffer() { delete[] data_; }
Buffer(const Buffer& o) : data_(new char[o.n_]), n_(o.n_) { // deep copy
std::memcpy(data_, o.data_, n_);
}
Buffer& operator=(Buffer o) { // copy-and-swap
std::swap(data_, o.data_);
std::swap(n_, o.n_);
return *this;
}
};Remember
- Raw owning pointers need copy control.
- Copy-and-swap gives strong exception safety.
- Prefer rule of zero.
Interview questions
Shallow vs deep copy?
Shallow copies pointer values so both objects share memory; deep copy allocates new memory and copies the contents.
When is the copy constructor called?
Initialising from another object, passing/returning by value (unless elided) and throwing by value.
Lesson test
Take an 8-question test on “Copy Control: Rule of 3/5/0” — concepts, output prediction, bug spotting and interview questions.