The idea: an object lives as long as its scope
In C++ a local object is born when its declaration runs. Its constructor runs then. It dies when the closing brace of its block is reached. Its destructor runs then. You never call either one by hand. When several objects end at the same brace, they are destroyed in the reverse order of construction: the last one built is the first one destroyed (Demo 1).
The canvas follows one small class, Buffer, through five short programs. The left side
shows the program and every special call, in order. The middle shows the objects on the stack; the
right shows the heap blocks they point at. Pick a class version and a program, then press
Run. A grey box carries each value, one hop per step.
A class that owns memory
Buffer holds a size and a pointer to an int array on the heap. The
constructor allocates the array; the destructor frees it. That pairing is RAII: the
resource lives exactly as long as the object.
class Buffer {
int n;
int *data;
public:
explicit Buffer(int n) : n(n), data(new int[n]) {
for (int i = 0; i < n; i++) data[i] = 10 * (i + 1);
}
~Buffer() { delete[] data; }
int& operator[](int i) { return data[i]; }
};
Here Buffer a(3) owns the block at 0x2000 holding 10, 20, 30. Where the stack
and heap live, and what new and delete do with addresses, is on
C++ Pointers and Stack vs Heap in C.
The default copy is shallow
If you write no copy constructor, the compiler writes one for you. It copies each member as it is.
For n that is fine. For data it copies the address, not the ints.
After Buffer b = a; both objects hold 0x2000 (Demo 2).
Two things then go wrong. First, b[0] = 9 also changes a[0], because there
is only one array. Second, at the closing brace ~b frees 0x2000, and then
~a frees it again. That is a double free: undefined behaviour. Most
allocators abort the program with a message such as free(): double free detected. The page
marks the second delete[] with a cross and skips it.
The rule of three
The rule of three says: if a class needs a user-written destructor, it almost certainly needs a user-written copy constructor and copy assignment operator too. The destructor is the sign that the class owns something, and the default copies do not know that.
Buffer(const Buffer& o) : n(o.n), data(new int[o.n]) {
for (int i = 0; i < n; i++) data[i] = o.data[i];
}
This is a deep copy: b gets its own block at 0x2010 with the
same values. Now b[0] = 9 leaves a at 10, 20, 30, and each destructor frees its
own block once (Demo 3). Pass by Value vs Pass by
Reference shows the same shallow/deep difference for nested lists in other languages.
Copy assignment: the target already owns a block
b = a; is not a construction: b already exists and owns 0x2010.
The compiler's operator= just overwrites b.data with 0x2000. The
old block now has no owner, so it leaks, and 0x2000 is again freed twice
(Demo 4). A correct version has three jobs:
Buffer& operator=(const Buffer& o) {
if (this != &o) { // a = a must not free its own data
int *p = new int[o.n]; // 1. make the new copy first
for (int i = 0; i < o.n; i++) p[i] = o.data[i];
delete[] data; // 2. free the old block
data = p; n = o.n; // 3. take the new one
}
return *this;
}
In Demo 5 it builds 0x2020, frees 0x2010, and then
~b frees 0x2020 and ~a frees 0x2000. Copying before
deleting also means a failed new leaves b unchanged.
| Program | Calls with the compiler's copies | Calls with the rule of three |
|---|---|---|
Buffer b = a; | ctor a, copy b (pointer), ~b, ~a ✗ double free | ctor a, copy b (new 0x2010), ~b, ~a ✓ |
b = a; | ctor a, ctor b, operator= (pointer), ~b, ~a ✗ leak + double free | ctor a, ctor b, operator= (new 0x2020), ~b, ~a ✓ |
show(a); | ctor a, copy x, ~x, ✗ use after free, ~a ✗ double free | ctor a, copy x (new 0x2010), ~x, ~a ✓ |
Passing by value is a copy too
void show(Buffer x) takes its parameter by value, so show(a) runs the copy
constructor to build x. With the shallow copy, x shares a's block,
and when show returns, ~x frees it. Back in the caller, a now holds
a dangling pointer: a[0] = 1 writes to freed memory, and ~a frees it a second
time (Demo 6). Nothing in the call looks like a copy, which is why this bug is easy to miss.
Taking const Buffer& avoids the copy altogether.
Moving instead of copying
A copy is wasteful when the source is about to die anyway. C++11 adds the move
constructor, Buffer(Buffer&& o). It takes the pointer itself and leaves the
source empty:
Buffer(Buffer&& o) noexcept : n(o.n), data(o.data) {
o.data = nullptr; o.n = 0;
}
std::move(a) moves nothing by itself. It only casts a to an rvalue, so that a
move constructor can be chosen. If the class has none, the call quietly falls back to the copy
constructor, because const Buffer& accepts an rvalue too (Demo 7: a deep copy
to 0x2010). A user-written destructor or copy operation stops the compiler from writing a
move constructor for you. With one (Demo 8), b takes 0x2000 and
a is left "moved-from" with nullptr. ~a then runs
delete[] nullptr, which does nothing. The destructor, two copy operations and two move
operations together are the rule of five.
The rule of zero
The best fix is often to write none of the five. If Buffer held a
std::vector<int> or a std::unique_ptr<int[]> instead of a raw
pointer, the compiler's copies and moves would already do the right thing (unique_ptr
makes the class move-only). Write the special members only in the one small class that manages the
resource. How destructors run while an exception unwinds the stack is on
Exception Unwinding.
See also C++ Pointers for addresses, new,
delete and dangling pointers, Stack vs Heap in C for what a
double free does inside the allocator, Malloc Allocators for how
the heap hands out blocks, and Pass by Value vs Pass by Reference.
See also Arrays and C-Strings in Memory for what a char buffer and strcpy do byte by byte.
See also C++ object layout under inheritance for object slicing, when a derived object is copied into a base by value.
What the page leaves out
Real heap addresses look like 0x6000008c8040; the page uses 0x2000,
0x2010, 0x2020 (16 bytes apart, as the real allocator handed them out in a test
run) and never reuses a freed block. A real program usually aborts at the first double free; the page
skips it and goes on. Left out: copy elision and return value optimisation (no program here returns an
object), the move assignment operator in action, copy-and-swap, = default and
= delete, exception safety in detail, arrays of objects, inheritance and virtual
destructors, and the exact point where a by-value parameter is destroyed (the end of the call or of
the full expression, depending on the compiler).