oops · high
Rule of 0 / 3 / 5
C++ gives every class five special members (destructor, copy ctor, copy assignment, move ctor, move assignment). Own no raw resource and you should declare none — the Rule of 0. The moment you hand-manage a resource you must define all five (the Rule of 5): a custom destructor/copy suppresses the implicit moves, and a custom move implicitly deletes the copies. The clean fix is almost always to store the resource in an RAII member (unique_ptr, vector, string), which returns you to the Rule of 0.
If a class manages a raw resource you must define all five special members (Rule of 5) and declaring some suppresses/deletes the rest; if it owns nothing raw, declare none (Rule of 0) and let the compiler generate them — push ownership into RAII members to stay there.
The code
struct Widget { std::string name; int qty;}; // Rule of 0: no special members
class Buf { // owns a RAW resource int* p; // raw pointer -> default copy is shallowpublic: explicit Buf(std::size_t n) : p(new int[n]) {} ~Buf() { delete[] p; } // (3) destructor Buf(const Buf& o); // (3) copy ctor Buf& operator=(const Buf& o); // (3) copy assign Buf(Buf&& o) noexcept; // (5) move ctor Buf& operator=(Buf&& o) noexcept; // (5) move assign};
class Good { std::unique_ptr<int[]> p;}; // Rule of 0 done right (RAII member)What this lesson walks through
- 01Rule of 0: write none, get all five
- 02A raw resource breaks the defaults
- 03Rule of 3 — and what it SUPPRESSES
- 04Rule of 5: bring the two moves back
- 05The interaction cuts both ways: a move DELETES the copies
- 06Rule of 0 done right: RAII members
- 07The rule in one breath
Every class has five special members: destructor, copy ctor, copy assignment, move ctor, move assignment. Declare none and own no raw resource, and the compiler generates all five correctly. That's the Rule of 0 — 0 of 5 declared — and it's the goal. Watch the badge: it counts how many of the five YOU control.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Rule of 0 / 3 / 5 and 100+ animated C++ interview lessons.