What is the Rule of Three, Five and Zero in C++?
| Rule | Meaning |
|---|---|
| Rule of Zero | Do not write special member functions. Let std::string, vector and smart pointers handle the resources |
| Rule of Three | If you need a custom destructor, copy constructor or copy assignment, you probably need all three |
| Rule of Five | Add 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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |