Rule of Three — if you need one of destructor, copy constructor, copy assignment, you likely need all three.
1class MyClass {2private:3 int* data;45public:6 // Constructor7 MyClass(int value) {8 data = new int(value);9 }1011 // Destructor12 ~MyClass() {13 delete data;14 }1516 // Copy constructor17 MyClass(const MyClass& other) {18 data = new int(*other.data);19 }2021 // Copy assignment22 MyClass& operator=(const MyClass& other) {23 if (this != &other) {24 *data = *other.data;25 }26 return *this;27 }28};
Rule of Five (C++11):
Rule of Zero (best):
1class MyClass {2 std::unique_ptr<int> data;3public:4 MyClass(int value) : data(std::make_unique<int>(value)) {}5 // Destructor, copy, move — all auto-generated!6};