Rule of five (C++)

The rule of five (known as the rule of three before C++11) are rules of thumb in C++ for the building of exception-safe code and for formalizing rules on resource management. The rules prescribe how the default members of a class should be used to achieve these goals systematically.

Special member functions

The rule of five (also known as the law of the big five or the big five; before C++11, it was three rather than five) is a rule of thumb in C++ that claims that if a class defines any of the following then it should probably explicitly define all five:

These five functions are special member functions. If one of these functions is used without first being declared by the programmer it will be implicitly implemented by the compiler with the following default semantics:

The rule of five states that if one of these had to be defined by the programmer, it means that the compiler-generated version does not fit the needs of the class in one case and it will probably not fit in the other cases either. The term "Rule of three" was coined by Marshall Cline in 1991.

An amendment to this rule is that if the class is designed in such a way that resource acquisition is initialization (RAII) is used for all its (nontrivial) members, the destructor may be left undefined (prior to C++11, this was known as The Law of The Big Two). A ready-to-go example of this approach is the use of smart pointers instead of plain ones.

Because implicitly-generated constructors and assignment operators simply copy all class data members ("shallow copy"), one should define explicit copy constructors and copy assignment operators for classes that encapsulate complex data structures or have external references such as pointers, if you need to copy the objects pointed to by the class members. If the default behavior ("shallow copy") is actually the intended one, then an explicit definition, although redundant, will be "self-documenting code" indicating that it was an intention rather than an oversight. C++11 introduces a default special member function syntax for specifying that a default function is desired without having to type out the function body.

See also