⚙️ C++ Intermediate

What is the Rule of Three/Five/Zero in C++?

Answer

These rules guide when and how to implement special member functions (constructor, destructor, copy/move operations): Rule of Three (pre-C++11): if you define any of these three, define all three: (1) Destructor, (2) Copy constructor, (3) Copy assignment operator. Needed when a class manually manages a resource (raw pointer, file handle). class String { char* data; size_t len; public: ~String() { delete[] data; } // Destructor String(const String& o) : data(new char[o.len+1]), len(o.len) { std::memcpy(data, o.data, len+1); } // Copy ctor String& operator=(const String& o) { // Copy assign if (this != &o) { delete[] data; data = new char[o.len+1]; len = o.len; std::memcpy(data, o.data, len+1); } return *this; } };. Rule of Five (C++11+): if you define any of the three above, also define: (4) Move constructor, (5) Move assignment operator — for efficiency: String(String&& o) noexcept : data(o.data), len(o.len) { o.data = nullptr; o.len = 0; } String& operator=(String&& o) noexcept { if (this != &o) { delete[] data; data = o.data; len = o.len; o.data = nullptr; o.len = 0; } return *this; }. Rule of Zero (preferred): design classes so they don't need any custom special member functions — use RAII wrappers (smart pointers, std::string, std::vector) as members. The compiler-generated versions will be correct: class Person { std::string name; // Handles its own memory int age; std::unique_ptr<Address> address; // Owns address }; // No special member functions needed!. The Rule of Zero is the cleanest — prefer it by using standard containers and smart pointers as members.