What is the rule of three?

And related to this: What is the rule of five? And what is the rule of zero?

When you need to implement either a destructor, a copy constructor, of an assignment operator, then the rule of three says that you really need to implement all three of these methods. If you don’t, then the compiler will provide a default implementation for you. And if you’re declaring and implementing a destructor, for example, because you need to clean-up some resources, then you’re almost certainly going to want to manage those resources when you make a copy of your object and when you assign one object instance to another.

The rule of five is a more modern version of the rule of three and it adds two more methods that should be implemented together with the other three. This involve move semantics and the methods are the move copy constructor and the move assignment operator.

The rule of zero is really just the same thing stated the other way around. This says that when you don’t need these methods, then don’t declare any of them. But what if you have a class that otherwise would not need these methods but because it’s intended to serve as a base class, then it needs a virtual destructor? In this case, you’re adding a destructor not for managing resources, but just to enable polymorphism to work properly through the base class. When you have to declare a destructor like this, then the rule of zero says that you should go ahead and declare the other four methods, the copy constructor, the move copy constructor, the assignment operator, and the move assignment operator, and specify that they should all be default. This will signal the compiler to provide them for you as if you had not declared any of them.