Rule of 5, 3, 0 in C++

Rule of 5, 3, 0 in C++

Tags
c++
Published
April 29, 2020
Author
Chris Chan

Rule of 5, 3, 0

In C++ there are six functions that pertain to the lifecycle management of an object: constructor, copy constructor, copy assignment operator, move constructor, move assignment operator and the destructor. For any of the aforementioned functions, the compiler will generate an implementation for you if you do not declare or delete them. The snippet below demonstrates each of these operators.
class MyClass { public: // constructor // calls default constructor of each class member and of base class MyClass() = default; // copy constructor // calls copy constructor of each class member and of base class MyClass(MyClass const& other) = default; // copy assignment // calls copy assignment of each class member and of base class MyClass& operator=(MyClass const& other) = default; // move constructor // calls move constructor of each class member and base class MyClass(MyClass&& other) = default // move assignment // calls move assignment of each class member and base class MyClass& operator=(MyClass&& other) = default; // destructor // calls the destructor of each class member and base class ~MyClass() = default; }; // Equivalently class MyClass{ };
There are three important rules surrounding when and how we should use these functions:
  1. Rule of Three
  1. Rule of Five
  1. Rule of Zero

Rule of Three

  • The Rule of Three states that: if your class requires a user-defined destructor, copy constructor or a copy assignment operator, then you should define all three functions.
  • The aforementioned functions are user-defined when a class is managing a resource of non-object type (e.g. raw pointer or file descriptor) so the author will have to instruct the compiler on how to allocate/deallocate the resource.

Rule of Five

  • The Rule of Five states that: if you define a move constructor or move assignment operator, then you should define both functions in addition to the functions involved in the Rule of Three (destructor, copy constructor and copy assignment operator).
  • The Rule of Five is a modern version of the Rule of Three since it was only in C++11 that the move semantics was introduced.

Rule of Zero

  • The Rule of Zero states that: if your class does not require a copy/move constructor, a copy/move assignment operator, or a custom destructor then do not define them. This is often the case for classes where all its members have the five aforementioned functions defined.
  • Generally speaking, classes that deal with ownership will have the aforementioned five functions defined. Otherwise, they should not be defined.