C++之Rule of Zero

Classes that have custom destructors, copy/move constructors or copy/move assignment operators should deal exclusively with ownership (which follows from the Single Responsibility Principle). Other classes should not have custom destructors, copy/move constructors or copy/move assignment operators. [1]

class rule_of_zero {
  std::string cppstring;

  rule_of_zero(const std::string& arg) : cppstring(arg) {}

When a base class is intended for polymorphic use, its destructor may have to be declared public and virtual. This blocks implicit moves (and deprecates implicit copies), and so the special member functions have to be declared as defaulted [2]

class base_of_five_defaults {
  base_of_five_defaults(const base_of_five_defaults&) = default;
  base_of_five_defaults(base_of_five_defaults&&) = default;
  base_of_five_defaults& operator=(const base_of_five_defaults&) = default;
  base_of_five_defaults& operator=(base_of_five_defaults&&) = default;
  virtual ~base_of_five_defaults() = default;

however, this can be avoided if the objects of the derived class are not dynamically allocated, or are dynamically allocated only to be stored in a std::shared_ptr (such as by std::make_shared): shared pointers invoke the derived class destructor even after casting to std::shared_ptr<Base>.

Terry Tang
Terry Tang
Software Development Engineer

My research interests include distributed robotics, mobile computing and programmable matter.

comments powered by Disqus