5.2.13 · D3C++ Programming

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

2,332 words11 min readBack to topic

This page walks the RAII idiom through every kind of situation it must survive. The parent note told you what RAII is; here we prove it by hitting every corner case — the happy path, the exception path, the double-owner trap, the empty resource, the nested scope, and an exam-style twist.

Before each example, forecast: guess the answer yourself. Then check.


The scenario matrix

Every "resource lifetime" problem falls into one of these cells. We will hit each one.

Cell What triggers it The danger if RAII is absent Example
A. Normal exit function returns cleanly none (but hand-cleanup is verbose) Ex 1
B. Exception exit a callee throws mid-function resource leaks / stays locked Ex 2
C. Early return / break if(...) return; before cleanup skipped release Ex 3
D. Copy of an owner one owner assigned/copied to another double-free Ex 4
E. Move (steal) ownership transferred double-free OR no free Ex 5
F. Empty / null resource acquisition failed or moved-from destructor must be a no-op Ex 6
G. Nested / reverse order several owners in one scope wrong teardown order → use-after-free Ex 7
H. Real-world word problem file + lock together leak + deadlock combined Ex 8
I. Exam twist (throwing dtor) destructor throws while unwinding std::terminate Ex 9

Each cell letter appears as a tag on its example. Together they tile the whole space of things that can go wrong when a resource is acquired.

Prerequisites we lean on: Constructors and Destructors, Stack Unwinding and Exceptions, Smart Pointers - unique_ptr shared_ptr, Rule of Three Five Zero, Move Semantics, Exception Safety Guarantees, and std::lock_guard and Mutexes.


Counting model for the examples

To make cleanup checkable with numbers, imagine every resource keeps a global ledger:

Look at the figure: the black line traces live over time. RAII keeps it a clean staircase back down to 0.

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

The worked examples


Recall

Recall Which matrix cell is each danger?
  • Leak on an exception ::: Cell B — fixed by stack unwinding running the destructor.
  • Skipped cleanup on if(...) return; ::: Cell C — every exit path runs the destructor.
  • Same address freed twice ::: Cell D — default copy of a raw-pointer owner; fix with Rule of Five / unique_ptr.
  • Emptied object still safe to destroy ::: Cell F — destructor guards the null case (no-op).
  • std::terminate from cleanup ::: Cell I — throwing destructor during unwinding; make it noexcept.