首页 > 代码库 > Rule of three & Rule of five

Rule of three & Rule of five

Reference:http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)

The rule of three (also known as the Law of The Big Three or The Big Three) is a rule of thumb in C++ that claims that if a class defines one of the following it should probably explicitly define all three:[1]

  • destructor
  • copy constructor
  • copy assignment operator

These three 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 default semantics of performing the said operation on all the members of the class. The default semantics are:

  • Destructor - Call the destructors of all the object‘s class-type members
  • Copy constructor - Construct all the object‘s members from the corresponding members of the copy constructor‘s argument, calling the copy constructors of the object‘s class-type members, and doing a plain assignment of all non-class type (e.g., int or pointer) data members
  • Copy assignment operator - Assign all the object‘s members from the corresponding members of the assignment operator‘s argument, calling the copy assignment operators of the object‘s class-type members, and doing a plain assignment of all non-class type (e.g., int or pointer) data members.

the rule of five we have the following special members:

  • destructor
  • copy constructor
  • move constructor
  • copy assignment operator
  • move assignment operator