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).

Six lines of code: an outer block with Buffer a(3), an inner block with Buffer b(2). Next to each line, the call it makes: Buffer(3) for a allocates 0x2000, Buffer(2) for b allocates 0x2010, the inner closing brace runs the destructor of b and deletes 0x2010, the outer closing brace runs the destructor of a and deletes 0x2000. Two vertical bars show a alive for longer than b.
Constructors run at the declaration, destructors at the closing brace, in reverse order.

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 panels. Left, the compiler's shallow copy, marked with a cross: a and b both hold data = 0x2000 and both arrows go to one block 10, 20, 30, which will be deleted twice. Right, the rule of three deep copy, marked with a check: a holds 0x2000, b holds 0x2010, and each points at its own block 10, 20, 30.
A shallow copy gives one block two owners. A deep copy gives each object its own block.

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.

ProgramCalls with the compiler's copiesCalls with the rule of three
Buffer b = a;ctor a, copy b (pointer), ~b, ~a ✗ double freector a, copy b (new 0x2010), ~b, ~a ✓
b = a;ctor a, ctor b, operator= (pointer), ~b, ~a ✗ leak + double freector a, ctor b, operator= (new 0x2020), ~b, ~a ✓
show(a);ctor a, copy x, ~x, ✗ use after free, ~a ✗ double freector 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;
}
Two panels. Before: a holds data = 0x2000 and points at the block 10, 20, 30; b does not exist yet. After Buffer b = std::move(a): a holds data = nullptr, b holds data = 0x2000 and points at the same block. No new and no copy.
A move hands the block from a to b and leaves a holding nullptr.

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).

On the mind map

Open the Operating Systems mind mapOperatingSystemsBoot and program start: from power on to main()Boot and program startProcesses and the kernel: how user code talks to the kernelProcesses and the kernelInterrupts and devices: hardware interrupts the CPUInterrupts and devicesScheduling and deadlock: who runs next, who gets whatScheduling and deadlockVirtual memory: every address is translatedVirtual memoryPhysical memory: who gets which bytes of RAMPhysical memoryFiles and storage: from open() down to the diskFiles and storageDisks and RAID: blocks down to platter or flashDisks and RAIDIsolation and security: limit what a process can doIsolation and securityStack vs heap in CStack vs heap in Cframes pop on return, malloc needs freeC++ PointersC++ Pointersp holds an address; p + 1 adds sizeofArrays and C-stringsArrays and C-stringsa[i] = base + i·sizeofRule of threeOwn a pointer? Write dtor, copy, assignStruct paddingStruct paddingLargest alignment first leaves no gapsEndiannessEndiannessx86 stores the low byte firstBuddy allocatorBuddy allocatorsplit in halves, find the buddy with XORFit StrategiesFit Strategiesfirst, next, best, worst: none always winsReclaim and OOM killerReclaim and OOM killerkswapd reclaims, then the OOM killerSlab allocatorSlab allocatorkmalloc: per-CPU freelists of fixed sizesmalloc vs jemalloc vs tcmallocmalloc vs jemalloc vs tcmallocper-thread caches avoid arena lock fightsSwap out and swap inSwap out and swap inCold anon pages go to disk, fault backOpen the Operating Systems mind mapOperating Systemswho gets which bytes of RAMPhysical memoryStack vs heap in CStack vs heap in Cframes pop on return, malloc needs freeC++ PointersC++ Pointersp holds an address; p + 1 adds sizeofArrays and C-stringsArrays and C-stringsa[i] = base + i·sizeofRule of threeOwn a pointer? Write dtor, copy, assignStruct paddingStruct paddingLargest alignment first leaves no gapsEndiannessEndiannessx86 stores the low byte firstBuddy allocatorBuddy allocatorsplit in halves, find the buddy with XORFit StrategiesFit Strategiesfirst, next, best, worst: none always winsReclaim and OOM killerReclaim and OOM killerkswapd reclaims, then the OOM killerSlab allocatorSlab allocatorkmalloc: per-CPU freelists of fixed sizesmalloc vs jemalloc vs tcmallocmalloc vs jemalloc vs tcmallocper-thread caches avoid arena lock fightsSwap out and swap inSwap out and swap inCold anon pages go to disk, fault back
This page on the Operating Systems mind map · 66 pages in 9 branches · open it to see the whole map and test yourself in recall mode.