The Rule of Three
What is the Rule of Three?
The Rule of Three is a guideline in C++ that states if a class needs to define one of the following special member functions, it should probably define all three:
These functions are required when a class manages a resource such as memory, file handles, or network connections, and you need to define how these resources are handled during copying and destruction.
For example, consider a class that manages a dynamically allocated array:
class DynamicArray {
public:
DynamicArray(size_t size) : size_(size), data_(new int[size]) {}
// Copy constructor
DynamicArray(const DynamicArray& other) : size_(other.size_), data_(new int[other.size_]) {
std::copy(other.data_, other.data_ + size_, data_);
}
// Copy assignment operator
DynamicArray& operator=(const DynamicArray& other) {
if (this != &other) {
delete[] data_;
size_ = other.size_;
data_ = new int[size_];
std::copy(other.data_, other.data_ + size_, data_);
}
return *this;
}
// Destructor
~DynamicArray() {
delete[] data_;
}
private:
size_t size_;
int* data_;
};
In this example, the class follows the Rule of Three by defining a copy constructor, copy assignment operator, and destructor to handle the memory allocation and deallocation properly.