0Pricing
C++ Academy · Lesson

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

  1. The RAII Principle
  2. Destructors and Cleanup
  3. Rule of Three/Five
  4. Scope Guards
← Back to C++ Academy