Difficulty: Advanced
What are the rule of three, rule of five and rule of zero? Show how you would apply them to a class that owns a dynamic array.
This is the question that reveals whether you can write a resource-owning class correctly. Let's build up the rules from the underlying problem.
Suppose your class owns a raw heap buffer. The compiler-generated copy constructor and copy assignment copy the pointer, not the data, so two objects end up pointing to the same buffer, and when both destructors run you get a double free. The rule of three says: if your class needs a user-defined destructor, copy constructor, or copy assignment operator, it almost certainly needs all three. The destructor is a hint that you own something, and the copy operations must then duplicate it properly (deep copy).
C++11 added move semantics, so the rule became the rule of five: add a move constructor and a move assignment operator. Without them, the class still works, since copies are used as a fallback, but you lose the performance of cheaply transferring ownership from temporaries. Moves should leave the source in a valid empty state (null pointer, size zero) so its destructor is safe, and they should be noexcept.
The copy assignment has a well-known pitfall: self-assignment and exception safety. A neat solution is copy-and-swap: take the parameter by value, swap it with *this, and let the parameter's destructor clean up the old data. It gives the strong exception guarantee and handles self-assignment for free, at the price of one extra move.
Now the best rule: the rule of zero. Design your classes so that they do not manually manage resources at all. Hold members that manage themselves, like std::vector, std::string and std::unique_ptr, and write none of the five special functions. The compiler-generated ones do the right thing, because each member knows how to copy or move itself. In practice, this is the default you should aim for. Only tiny, focused wrapper classes (your own smart pointer or buffer) should implement the rule of five.
Two side notes interviewers enjoy: a polymorphic base class needs a virtual destructor, and once you declare that destructor, implicit moves are suppressed, so you may need to '= default' the other special members explicitly. And '= delete' is a valid way to express non-copyable types.
A good closing sentence is: 'I follow the rule of zero by default, and when I write a resource-owning wrapper I implement all five, using copy-and-swap or explicit self-assignment checks.'
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
class Buffer {
int* data_;
std::size_t n_;
public:
explicit Buffer(std::size_t n) : data_(new int[n]()), n_(n) {}
~Buffer() { delete[] data_; } // 1. destructor
Buffer(const Buffer& o) : data_(new int[o.n_]), n_(o.n_) { // 2. copy ctor
std::copy(o.data_, o.data_ + n_, data_);
}
Buffer& operator=(Buffer o) noexcept { swap(o); return *this; } // 3. copy/move assign (copy-and-swap)
Buffer(Buffer&& o) noexcept : data_(o.data_), n_(o.n_) { // 4. move ctor
o.data_ = nullptr; o.n_ = 0;
}
void swap(Buffer& o) noexcept { std::swap(data_, o.data_); std::swap(n_, o.n_); }
std::size_t size() const { return n_; }
};
// Rule of zero: nothing to write, vector handles everything.
struct Better { std::vector<int> data; };
int main() {
Buffer a(3);
Buffer b = a; // deep copy
Buffer c = std::move(a); // steals a's buffer
std::cout << a.size() << " " << b.size() << " " << c.size() << "\n";
Better x{{1, 2, 3}};
Better y = x; // compiler-generated copy is correct
std::cout << y.data.size() << "\n";
}
The single by-value assignment operator serves as both copy and move assignment. Moved-from Buffer a reports size 0 and is safe to destroy.
rule of three, rule of five, rule of zero, move semantics, resource management