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

RuleMeaning
Rule of ZeroDo not write special member functions. Let std::string, vector and smart pointers handle the resources
Rule of ThreeIf you need a custom destructor, copy constructor or copy assignment, you probably need all three
Rule of FiveAdd the move constructor and move assignment to the three
#include <iostream>
#include <string>
#include <vector>

struct Person {                                   // Rule of Zero: no special functions written
    std::string name;
    std::vector<int> scores;
};

int main() {
    Person a{"Riya", {80, 90}};
    Person b = a;                                  // a correct copy, made by the compiler
    Person c = std::move(a);                       // a correct move
    std::cout << b.name << ' ' << b.scores.size() << ' ' << c.name << ' ' << a.name.empty() << '\n';
}
Output

Riya 2 Riya 1

See Move Semantics and the Rule of Five.


Learn more about the similar topics:
Tutorials
C++ Lambda Expressions
C++ Move Semantics and the Rule of Five
Modern C++ Features: ranges, optional, variant and format
C++ Multithreading: thread, mutex and async
Exercises & Assignments
Filter and sum numbers with algorithms and ranges
Interview Questions & Answers
What is the Rule of Three, Five and Zero in C++?
What does std::move do in C++?
What are concepts in C++20?
What is perfect forwarding in C++ (std::forward)?
How do lambda captures work in C++?
What is new in C++20?
What is new in C++23?