5.2.13 · D1C++ Programming

Foundations — RAII — resource acquisition is initialization — why it's the key idiom

1,599 words7 min readBack to topic

This page builds every word the parent note RAII topic leans on, from absolute zero. If you have never written a C++ class, start here.


0. What is a "resource"?

Picture a library book. You check it out (acquire) and must return it (release). If you never return it, nobody else can borrow it — the book is "leaked".

Figure — RAII — resource acquisition is initialization — why it's the key idiom

Examples of resources, all following the same borrow-return shape:

Resource "Check out" "Return"
Heap memory new delete
File fopen fclose
Lock lock() unlock()

Why the topic needs this: RAII is entirely about making the "return" step automatic. If you don't feel the acquire→release rhythm in your bones, nothing later makes sense.


1. The stack, scope, and { }

The { and } are not decoration — they are birth and death markers.

{
    int x = 5;   // x is born here
    // ... x usable ...
}                // x DIES here — its slot is reclaimed
// x no longer exists
Figure — RAII — resource acquisition is initialization — why it's the key idiom

Why "stack"? Like a stack of plates: you can only add or remove from the top. The last plate placed is the first plate taken. This last-in-first-out order is exactly why later objects are destroyed before earlier ones (parent's Example 3).

Why the topic needs this: RAII "ties a resource to an object on the stack." That sentence is meaningless until you know a stack object automatically dies at the closing brace — that automatic death is the hook RAII hangs its cleanup on.


2. Objects, and the two special functions

The ~ (tilde) means "the opposite of the constructor" — the undo function.

class Book {
public:
    Book()  { /* checkout: acquire */ }   // constructor — runs at birth
    ~Book() { /* return:  release  */ }   // destructor — runs at death
};

Why the topic needs this: these two functions ARE RAII. See Constructors and Destructors for the full mechanics.


3. Pointers, new, delete, and nullptr

Figure — RAII — resource acquisition is initialization — why it's the key idiom
  • new T asks the system for fresh heap memory and returns a pointer to it (acquire).
  • delete p gives that memory back (release).
  • nullptr is the special "points at nothing" address — a pointer deliberately aimed at the void.

Why the topic needs this: heap memory is the classic resource. new/delete is the classic manual acquire/release that RAII replaces with unique_ptr — see Smart Pointers - unique_ptr shared_ptr.


4. Exceptions and stack unwinding

That "skipping every line below" is exactly what kills manual delete p; lines.

Figure — RAII — resource acquisition is initialization — why it's the key idiom

Look at the figure: even when the red "throw" bolt fires mid-function, the pale-yellow destructors of already-built objects still run on the way out. This guarantee is the engine of RAII. A raw delete p; sitting as a plain statement is not a destructor, so unwinding does not run it — but a unique_ptr's destructor is, so it does.

Why the topic needs this: stack unwinding is the single language promise that makes RAII exception-safe. Deeper: Stack Unwinding and Exceptions and Exception Safety Guarantees.


5. Copy, move, and "ownership"

Two things can accidentally create a second owner:

Why "steal then null"? After a move, the source must be harmless. Setting its pointer to nullptr means its destructor sees "points at nothing" and skips the delete — so the resource is freed once, by the new owner only.

Why the topic needs this: this is the reasoning behind the Rule of Five in the parent note. See Rule of Three Five Zero and Move Semantics.


Prerequisite map

Resource: acquire then release

RAII idiom

Scope and the stack

Objects with ctor and dtor

Pointers, new, delete, nullptr

Ownership: exactly one owner

Exceptions

Stack unwinding

Copy vs Move: Rule of Five

Each foundation feeds RAII: scope+objects give the hook, unwinding gives the guarantee, ownership gives the correctness rule.


Equipment checklist

What is a "resource" in one phrase?
Anything you must acquire and later release (memory, file, lock, socket).
What marks the birth and death of a stack variable?
The opening { (birth) and closing } (death) of its scope.
In what order do stack objects die?
Reverse of birth order — last constructed, first destroyed (LIFO).
Which function runs automatically at object birth? At death?
Constructor at birth; destructor (~ClassName) at death.
What does new return, and who must call delete?
A pointer to fresh heap memory; you must call delete yourself.
What is nullptr?
A pointer that deliberately points at nothing.
What does an exception skip?
Every line below the throw in the current function as it jumps out.
What is stack unwinding?
On leaving a scope, C++ runs living objects' destructors in reverse order before control exits.
What is the golden ownership rule?
Exactly one owner frees the resource exactly once.
Why can copying an owner cause a double free?
Both objects hold the same pointer, so both destructors call delete on it.
What does a move do to the source's pointer?
Sets it to nullptr so the source's destructor does nothing.