☕ Buy Me Coffee
← Back to Feed

The Rule of Three, Five, and Zero

The Rule of Five is a rule of thumb for Modern C++ (C++11 and later) regarding the design of classes that manage resources.

If you need to explicitly define any of the following, you likely need to define or =delete all five:

  1. Destructor: Clean up resources.
  2. Copy Constructor: Deep copy resources.
  3. Copy Assignment Operator: Handle a = b safely.
  4. Move Constructor: Efficiently transfer resources.
  5. Move Assignment Operator: Efficiently handle a = std::move(b).

The Rule of Zero

Modern C++ best practice: Design your classes so that they don't need any of these. Leverage RAII containers like std::vector or std::unique_ptr which already handle their own Rule of Five. This makes your class cleaner and less bug-prone.

class MyClass {
    std::string name; // Handles its own memory
    std::vector<int> data; // Handles its own memory
    // No destructor or copy/move constructors needed!
};

// FEEDBACK_LOOP.exe

0.0 / 5.0
FROM 0 PEERS
→ Login to rate