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:
- Destructor: Clean up resources.
- Copy Constructor: Deep copy resources.
- Copy Assignment Operator: Handle
a = bsafely. - Move Constructor: Efficiently transfer resources.
- 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!
};