Rule of Zero, Three, and Five
🔴 Advanced
📖 Definition
The C++ Rule of Control:
- Rule of 3 (C++98): If a class defines a custom Destructor, Copy Constructor, or Copy Assignment operator, it must explicitly define all three.
- Rule of 5 (C++11): Adding Move Constructor and Move Assignment operator.
- Rule of 0 (Modern C++ Best Practice): Design classes using smart pointers and STL containers so zero custom destructors or copy/move operations are required!
💡 Code Example
#include <iostream>
#include <memory>
#include <string>
// Rule of Zero: Uses std::string and smart pointers -> compiler generates correct special functions
class UserProfile {
private:
std::string username;
std::unique_ptr<int> userId;
public:
UserProfile(std::string name, int id)
: username(name), userId(std::make_unique<int>(id)) {}
};
int main() {
UserProfile u1("Aria", 42);
UserProfile u2 = std::move(u1); // Move generated automatically by compiler
std::cout << "Rule of Zero class created & moved safely.\n";
return 0;
}