Rule of Five, Rule of Zero
Learn
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.
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.
What does the Rule of Zero recommend, and when does it apply?
Go deeper ↓Ownership by diff