Rule of Three/Five
Manage copy and move correctly.
The Rule of Three
If a class needs a custom destructor, it almost always also needs a custom copy constructor and copy assignment. These three travel together.
Why Three?
A class managing a raw resource must define how it is destroyed, copied, and assigned — otherwise the compiler-generated shallow copies cause double frees.
#include <iostream>
class Bad {
int* p;
public:
Bad(int v) : p(new int(v)) {}
~Bad() { delete p; }
// default copy => two objects delete the same p!
};All lessons in this course
- The RAII Principle
- Destructors and Cleanup
- Rule of Three/Five
- Scope Guards