Rule of Five — extends Rule of Three with move semantics (C++11).
1class MyClass {2private:3 int* data;45public:6 // 1. Destructor7 ~MyClass() { delete data; }89 // 2. Copy constructor10 MyClass(const MyClass& other) {11 data = new int(*other.data);12 }1314 // 3. Copy assignment15 MyClass& operator=(const MyClass& other) {16 if (this != &other) {17 *data = *other.data;18 }19 return *this;20 }2122 // 4. Move constructor23 MyClass(MyClass&& other) noexcept {24 data = other.data;25 other.data = nullptr;26 }2728 // 5. Move assignment29 MyClass& operator=(MyClass&& other) noexcept {30 if (this != &other) {31 delete data;32 data = other.data;33 other.data = nullptr;34 }35 return *this;36 }37};
Move semantics:
&& — rvalue reference.std::move() — cast to rvalue.noexcept — important for optimizations.