“Know how to solve every problem that has been solved.” “What I cannot create, I do not understand.” — Richard Feynman

Rule of Five, Rule of Zero

Learn

Lesson 6 of 7 standard ~5 min

The compiler will silently generate a destructor, copy operations, and move operations for your class. For a class that owns a raw resource, those defaults are wrong — a shallow copy that double-frees, a move that dangles. The Rule of Five names the five members that must be reasoned about together; the Rule of Zero is how you avoid the whole problem.

First, the membership of the set.

standardMultiple choice

The Rule of Five says that if you write one of a certain set of special member functions, you should think about all five. Which set?

Now the punchline most C++ courses bury: you should almost never write the five. Here is the rule that replaces them.

standardMultiple choice

What does the Rule of Zero recommend, and when does it apply?

Go deeper ↓Ownership by diff