Rule of Zero, Three, Five

Guidelines for managing object resources.

1. Rule of Zero

  1. If a class doesn’t manage resources directly, it shouldn’t declare any special member functions.
  2. Rely on the compiler-generated defaults for these functions.

This simplifies the class design and reduces the likelihood of resource management bugs.

2. Rule of Three

A struct or class that manages resources should define these three special member functions:

  1. Destructor
  2. Copy constructor
  3. Copy assignment
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class MyClass {
private:
int* data;
size_t size;
public:
MyClass(size_t size) : data(new int[size]), size(size) {}

~MyClass() {
delete[] data;
}

MyClass(const MyClass& other) : data(new int[other.size]), size(other.size) {
std::copy(other.data, other.data + size, data);
}

MyClass& operator=(const MyClass& other) {
if (this != &other) {
delete[] data;
size = other.size;
data = new int[size];
std::copy(other.data, other.data + size, data);
}
return *this;
}
};

3. Rule of Five

It extends the Rule of Three to include move semantics.

  1. Destructor
  2. Copy constructor
  3. Copy assignment operator
  4. Move constructor
  5. Move assignment operator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class MyClass {
private:
int* data;
size_t size;
public:
MyClass(size_t size) : data(new int[size]), size(size) {}

~MyClass() {
delete[] data;
}

MyClass(const MyClass& other) : data(new int[other.size]), size(other.size) {
std::copy(other.data, other.data + size, data);
}

MyClass& operator=(const MyClass& other) {
if (this != &other) {
delete[] data;
size = other.size;
data = new int[size];
std::copy(other.data, other.data + size, data);
}
return *this;
}

MyClass(MyClass&& other) noexcept : data(other.data), size(other.size) {
other.data = nullptr;
other.size = 0;
}

MyClass& operator=(MyClass&& other) noexcept {
if (this != &other) {
delete[] data;
data = other.data;
size = other.size;
other.data = nullptr;
other.size = 0;
}
return *this;
}
};
Author

Joe Chu

Posted on

2024-07-18

Updated on

2024-07-18

Licensed under

Comments