现在先说一下这个规则或者说是最佳实践是什么:

Rule of five

Each class should explicitly define exactly one of the following set of special member functions:

  • None
  • Destructor, copy constructor, copy assignment operator

In addition, each class that explicitly defines a destructor may explicitly define a move constructor and/or a move assignment operator.

Usually, one of the following sets of special member functions is sensible:

  • None (for many simple classes where the implicitly generated special member functions are correct and fast)
  • Destructor, copy constructor, copy assignment operator (in this case the class will not be movable)
  • Destructor, move constructor, move assignment operator (in this case the class will not be copyable, useful for resource-managing classes where the underlying resource is not copyable)
  • Destructor, copy constructor, copy assignment operator, move constructor (because of copy elision, there is no overhead if the copy assignment operator takes its argument by value)
  • Destructor, copy constructor, copy assignment operator, move constructor, move assignment operator
  • That move constructor and move assignment operator won’t be generated for a class that explicitly declares any of the other special member functions (like destructor or copy-constructor or move-assignment operator).
  • That copy constructor and copy assignment operator won’t be generated for a class that explicitly declares a move constructor or move assignment operator.
  • And that a class with an explicitly declared destructor and implicitly defined copy constructor or implicitly defined copy assignment operator is considered deprecated.

如果没有注意到这些的话, 有些时候你会发现莫名的编译错误, Attempting to reference a deleted function. 你连错在哪都不知道.

Rule of Zero (RAII)

In C++ the destructors of objects with automatic storage duration are invoked whenever their scope ends. This property is often used to handle cleanup of resources automatically in a pattern known by the meaningless name RAII.

An essential part of RAII is the concept of resource ownership: the object responsible for cleaning up a resource in its destructor owns that resource. Proper ownership policies are the secret to avoid resource leaks…

总结一下就是: 持有资源的类应该负责销毁资源. 并且应该将堆资源交给类来管理.

reference

The rule of three/five/zero - cppreference.com c++ - Rule-of-Three becomes Rule-of-Five with C++11? - Stack Overflow