Sobes.tech
Junior — Middle

Can you explain the principle of the three-rule or its essence?

sobes.tech AI

Answer from AI

The Rule of Three in C++ states: if a class needs to explicitly define one of the three special methods — destructor, copy constructor, or copy assignment operator — then it probably needs to define all three. This is related to resource management (for example, dynamic memory). If a class owns resources, then to correctly copy and release resources, all three methods must be implemented to avoid memory leaks or double deletion.

Example:

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