# RAII and Resource Management

> Bind every resource invariant to an object lifetime so deterministic destructors, stack unwinding, and the Rule of Zero eliminate leaks by construction.

- **Source:** C++ Atlas (https://cppatlas.com/topics/raii-and-resource-management)
- **Track:** Classes
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [basic.stc.auto] (https://eel.is/c++draft/basic.stc.auto), [class.dtor] (https://eel.is/c++draft/class.dtor), [except.ctor] (https://eel.is/c++draft/except.ctor), [class.copy.ctor] (https://eel.is/c++draft/class.copy.ctor), [class.copy.assign] (https://eel.is/c++draft/class.copy.assign), [smartptr] (https://eel.is/c++draft/smartptr), [thread.lock.scoped] (https://eel.is/c++draft/thread.lock.scoped)
- **cppreference links:** [RAII](https://en.cppreference.com/w/cpp/language/raii), [The rule of three/five/zero](https://en.cppreference.com/w/cpp/language/rule_of_three), [Destructors](https://en.cppreference.com/w/cpp/language/destructor), [Exceptions](https://en.cppreference.com/w/cpp/language/exceptions), [std::unique_ptr](https://en.cppreference.com/w/cpp/memory/unique_ptr), [std::shared_ptr](https://en.cppreference.com/w/cpp/memory/shared_ptr), [std::scoped_lock](https://en.cppreference.com/w/cpp/thread/scoped_lock), [std::exchange](https://en.cppreference.com/w/cpp/utility/exchange)
- **Prerequisites:** constructors-and-initialization-order, copy-and-move

Resource Acquisition Is Initialization (RAII) is C++'s foundational pattern for making leaks impossible by construction. Despite the awkward historical name, the rule has nothing to do with memory alone and everything to do with **invariants**: every acquisition of a finite resource—heap allocations, file descriptors, mutex locks, database transactions, or temporary flag mutations—must be paired with an automatic object whose lifetime governs that resource.

## Invariants bound to object lifetime

Manual `acquire()` / `release()` pairs fail whenever a function grows an early `return`, a `break`, or a call that throws an exception. RAII replaces cleanup branches across every exit path with one invariant maintained inside a class boundary: the constructor acquires the resource (or throws before the object's lifetime ever begins), and the destructor releases it deterministically when the enclosing scope ends (`[basic.stc.auto]`).

> **Mental model.** An object either owns a valid resource handle or never finished constructing. Because C++ guarantees destructors run on normal scope exit, early return, and exception unwinding alike, cleanup becomes a structural property of lexical scope rather than caller discipline.

That principle scales beyond pointers to arbitrary state transitions. A `std::scoped_lock` acquires one or more mutexes in its constructor and unlocks them in reverse on exit without deadlock (`[thread.lock.scoped]`). A state-saving guard can capture a numeric flag or locale on construction and restore it unconditionally when destroyed.

## Deterministic destruction and stack unwinding

C++ defines exact destruction order at every boundary (`[class.dtor]`):

- **Block scope:** automatic variables are destroyed in the exact reverse order their constructors completed.
- **Class members and bases:** non-static data members are destroyed in reverse declaration order, followed by direct non-virtual base classes in reverse base-specifier order, and finally virtual bases in reverse initialization order.

Stack unwinding preserves this guarantee when exceptions fly.

> **Standardese.** Under `[except.ctor]`, if an exception exits a constructor before its closing brace, the object's lifetime never began, so its own destructor does not run; however, every already-constructed base subobject and data member is destroyed immediately in reverse order.

```cpp
#include <stdexcept>

struct Channel {
    explicit Channel(int id) {
        if (id < 0) throw std::runtime_error("invalid channel");
    }
    ~Channel() = default;
};

struct Bridge {
    Channel rx;
    Channel tx;
    Bridge(int in_id, int out_id) : rx(in_id), tx(out_id) {}
    // If tx throws, ~rx() runs automatically; ~Bridge() never executes.
};
```

In contrast, letting an exception escape a destructor is catastrophic. Since C++11, user-declared destructors are implicitly `noexcept(true)` unless explicitly annotated `noexcept(false)` or inheriting a throwing member/base destructor (`[class.dtor]`). Throwing out of a `noexcept` destructor—or throwing a second exception while stack unwinding is already active—invokes `std::terminate()` immediately. Keep destructors non-throwing, logging or swallowing teardown failures safely when necessary.

## The Rule of Zero and the Rule of Five

Separating business logic from low-level ownership yields two complementary rules that govern special member functions.

The **Rule of Zero** applies to virtually all application classes: compose your type from existing RAII handles (`std::string`, `std::vector`, `std::unique_ptr`, `std::jthread`) and declare *no* destructor, copy constructor, copy assignment operator, move constructor, or move assignment operator. The compiler automatically synthesizes optimal, exception-safe special members by forwarding to each member.

The **Rule of Five** applies strictly to low-level wrapper classes that directly manage a raw resource handle (such as an OS file descriptor). Because the compiler cannot guess how to duplicate or relinquish a raw `int` handle, declaring a custom destructor requires explicitly specifying all five special members (`~T`, copy ctor, copy assign, move ctor, move assign)—either implementing or `= delete`-ing copying while writing a `noexcept` move with `std::exchange`.

```cpp
#include <utility>
#include <vector>

class UniqueFd {
    int fd_ = -1;
public:
    explicit UniqueFd(int fd = -1) noexcept : fd_(fd) {}
    ~UniqueFd() {
        if (fd_ >= 0) { /* close(fd_) */ }
    }

    UniqueFd(const UniqueFd&) = delete;
    UniqueFd& operator=(const UniqueFd&) = delete;

    UniqueFd(UniqueFd&& other) noexcept
        : fd_(std::exchange(other.fd_, -1)) {}

    UniqueFd& operator=(UniqueFd&& other) noexcept {
        if (this != &other) {
            if (fd_ >= 0) { /* close(fd_) */ }
            fd_ = std::exchange(other.fd_, -1);
        }
        return *this;
    }
};

struct Session { // Rule of Zero: inherits move-only semantics cleanly
    UniqueFd socket;
    std::vector<int> backlog;
};
```

> **Pitfall.** Writing `~Widget() = default;` inside a class body counts as a **user-declared destructor** (`[class.copy.ctor]`). That single line silently suppresses implicit move constructor and move assignment generation, causing moves on `Widget` to fall back to expensive copies, and marks implicit copy generation deprecated (`[depr.impldec]`).

## Ownership vocabulary: unique_ptr, shared_ptr, and locks

Express ownership intent directly in the type system so readers and compilers verify lifetime contracts at compile time. Choosing the right standard handle clarifies both lifetime semantics and runtime cost:

| Handle type | Ownership model | Overhead vs raw handle | Typical use case |
| --- | --- | --- | --- |
| `std::unique_ptr<T, D>` | Exclusive, move-only | Zero with stateless deleter | Polymorphic objects, C handles |
| `std::shared_ptr<T>` | Shared reference count | Control block + atomic count | Graph/async shared lifetimes |
| `std::weak_ptr<T>` | Non-owning observer | Shares control block existence | Cache entries, breaking cycles |
| `std::scoped_lock<Ms...>` | Lexical multi-mutex guard | Stack-only RAII frame | Deadlock-free critical sections |

For C APIs such as `std::FILE*`, prefer a stateless functor deleter over a function pointer. Passing `&std::fclose` as the deleter type `int(*)(std::FILE*)` stores an extra 8-byte pointer inside every `std::unique_ptr`, whereas a stateless callable `struct FileCloser` collapses to zero bytes via empty base optimization or `[[no_unique_address]]`:

```cpp
#include <cstdio>
#include <memory>

struct FileCloser {
    void operator()(std::FILE* f) const noexcept {
        if (f) std::fclose(f);
    }
};

using UniqueFile = std::unique_ptr<std::FILE, FileCloser>;
static_assert(sizeof(UniqueFile) == sizeof(std::FILE*));
```

Always allocate with `std::make_unique` or `std::make_shared` rather than bare `new`. Beyond removing `new`/`delete` from user code, `std::make_shared` combines the control block and managed object into one allocation, and before C++17 calling `f(std::unique_ptr<A>(new A), may_throw())` risked leaking `A` if `may_throw()` ran between `new A` and `unique_ptr` construction.

## Failure modes: self-assignment, noexcept, and premature exit

Even well-written RAII wrappers break along three edge boundaries. First, **self-move assignment** (`a = std::move(a)`) and **self-copy assignment** (`a = a`) can occur in generic algorithms (`std::sort`, `std::swap` fallbacks). Guard resource release in `operator=` or implement copy-and-swap / move-and-swap so self-assignment remains safe. Second, mark move operations `noexcept`: containers like `std::vector` rely on `std::move_if_noexcept` to preserve the strong exception guarantee, falling back to `O(N)` copies if a move constructor can throw. Third, avoid abrupt termination calls (`std::abort()`, `std::_Exit()`, or `std::exit()` while stack locals remain live): `std::exit()` runs `thread_local` and static destructors, **never** unwinding automatic stack frames (`[basic.start.term]`). Return cleanly from `main` instead so every scope unwinds.

## What to remember

- Bind every resource invariant—not just heap memory—to an object whose constructor establishes validity and whose destructor releases it.
- Destructors run in reverse construction order; if a constructor throws, already-constructed bases and members unwind while the enclosing destructor does not run.
- Destructors are implicitly `noexcept`; never allow exceptions to escape a destructor.
- Follow the **Rule of Zero** in domain classes; follow the **Rule of Five** only in dedicated single-resource wrappers, using `std::exchange` and `noexcept` on moves.
- Never write `~T() = default;` gratuitously—a user-declared destructor suppresses implicit move operations.

## Concept Map Outline

- **RAII & Resource Safety:** Binding resource invariants to object lifetimes guarantees deterministic cleanup across every exit path.
  - **Core Principle:** Constructors establish resource invariants and destructors release them at lexical scope exit.
    - **Invariant Acquisition:** A successfully constructed RAII object always holds either a valid resource or a safe empty state.
    - **Scope-Exit Release:** Cleanup fires uniformly on fallthrough, early return, break, and exception unwinding.
    - **Non-Memory Resources:** RAII manages file descriptors, mutexes, sockets, transactions, and temporary state guards alike.
  - **Destruction Rules:** C++ prescribes strict reverse teardown ordering and implicit noexcept on destructors.
    - **Reverse Order:** Locals, members, and bases are destroyed in exact reverse order of construction completion.
    - **Implicit noexcept:** Destructors are implicitly noexcept(true) since C++11 unless explicitly overridden or inheriting throwing ones.
    - **std::terminate Trap:** Allowing an exception to escape a noexcept destructor immediately calls std::terminate.
  - **Exception Unwinding:** Exceptions unwind only completely constructed objects and subobjects.
    - **Completed Subobjects:** Every base or member whose constructor finished before a throw is destroyed automatically.
    - **No Partial Destructor:** When a class constructor throws, that class's own destructor never runs because lifetime never began.
    - **No Abrupt Exit Unwind:** Calling std::exit or std::abort bypasses automatic stack frame destructors.
  - **Special Members:** Ownership design separates zero-boilerplate composition from custom resource handles.
    - **Rule of Zero:** Domain classes hold standard RAII members and declare zero custom special member functions.
    - **Rule of Five:** Low-level resource wrappers declaring a destructor must explicitly define or delete copy and move operations.
    - **Suppressed Moves:** Any user-declared destructor—even = default—suppresses compiler-generated move operations.
    - **std::exchange Moves:** Transfer handles cleanly with std::exchange(other.handle, invalid) and mark moves noexcept.
  - **Standard Vocabulary:** Standard library smart pointers and lock guards encode ownership contracts directly in types.
    - **unique_ptr Deleters:** Stateless functor deleters preserve single-pointer size whereas function-pointer deleters add storage overhead.
    - **shared_ptr & weak_ptr:** Use shared ownership sparingly with make_shared and break reference cycles with weak_ptr.
    - **scoped_lock Guards:** Acquire multiple mutexes atomically without deadlock and release them automatically at scope exit.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.stc.auto], [class.dtor])

In what order are local variables and class data members destroyed when a scope exits?

A. Alphabetical by identifier name for members, declaration order for locals
B. Reverse order of construction completion for locals, and reverse declaration order for class members
C. Forward declaration order so earlier handles close before later ones
D. Unspecified order unless wrapped inside std::tuple

**Answer (B):** Reverse order of construction completion for locals, and reverse declaration order for class members

**Why:** Under [basic.stc.auto] and [class.dtor], block-scope objects unwind in exact reverse order of construction completion, while class members are destroyed in reverse order of declaration inside the class definition.

### Question 2 [warmup] ([class.copy.ctor], [class.copy.assign])

What is the hidden consequence of adding `~Packet() = default;` to a struct that holds a std::vector<std::byte>?

```cpp
struct Packet {
    std::vector<std::byte> payload;
    ~Packet() = default;
};
```

A. Nothing changes; = default leaves all implicitly generated special members identical
B. The vector cannot be destroyed unless std::destroy_at is called manually
C. The struct becomes non-copyable until copy operations are also defaulted
D. Implicit move constructor and move assignment are suppressed, so moves silently fall back to copying payload

**Answer (D):** Implicit move constructor and move assignment are suppressed, so moves silently fall back to copying payload

**Why:** Under [class.copy.ctor] and [class.copy.assign], any user-declared destructor—even `= default;`—prevents implicit declaration of the move constructor and move assignment operator, turning `std::move(pkt)` into a copy.

### Question 3 [tricky] ([except.ctor])

Assume Part(1) succeeds and Part(2) throws std::runtime_error during construction of Assembly. Which destructors run?

```cpp
struct Part {
    explicit Part(int id);
    ~Part();
};
struct Assembly {
    Part first;
    Part second;
    Assembly() : first(1), second(2) {}
    ~Assembly();
};
```

A. Only ~Part() for first runs; ~Part() for second and ~Assembly() do NOT run
B. ~Part() for both first and second run, followed by ~Assembly()
C. Only ~Assembly() runs to clean up both members
D. No destructors run because the expression failed before Assembly existed

**Answer (A):** Only ~Part() for first runs; ~Part() for second and ~Assembly() do NOT run

**Why:** Under [except.ctor], because Assembly's constructor exited via an exception, Assembly's lifetime never began and ~Assembly() never runs. Every already-completed subobject (here only first) is destroyed immediately.

### Question 4 [tricky] ([unique.ptr.single])

Why does `std::unique_ptr<std::FILE, FileCloser>` (with stateless functor `FileCloser`) typically match `sizeof(std::FILE*)`, whereas `std::unique_ptr<std::FILE, int(*)(std::FILE*)>` is larger?

```cpp
struct FileCloser {
    void operator()(std::FILE* f) const noexcept { if (f) std::fclose(f); }
};
using P1 = std::unique_ptr<std::FILE, FileCloser>;
using P2 = std::unique_ptr<std::FILE, int(*)(std::FILE*)>;
```

A. std::unique_ptr uses std::shared_ptr's control block whenever a function pointer is passed
B. Function pointers disable move semantics, forcing std::unique_ptr to allocate a flag
C. P2 must store the runtime function pointer address inside the smart pointer, while stateless FileCloser takes zero bytes via empty-base / [[no_unique_address]] optimization
D. FileCloser deletes the pointer at compile time during constexpr evaluation

**Answer (C):** P2 must store the runtime function pointer address inside the smart pointer, while stateless FileCloser takes zero bytes via empty-base / [[no_unique_address]] optimization

**Why:** A function pointer type `int(*)(std::FILE*)` is stateful runtime data (different pointers share the same type), so unique_ptr must store it. A stateless functor encodes the deleter in the type itself and occupies zero extra bytes.

### Question 5 [standardese] ([class.dtor], [except.spec])

What happens in C++23 if a user-declared destructor `~Guard() { cleanup(); }` (with no exception specification) throws an exception at runtime during normal scope exit?

```cpp
struct Guard {
    ~Guard() { throw std::runtime_error("boom"); }
};
```

A. The exception propagates normally to the caller's catch block because noexcept was not written
B. std::terminate() is called because user-declared destructors are implicitly noexcept(true)
C. The compiler rejects ~Guard() at compile time whenever throw appears inside a destructor
D. Only throws during stack unwinding terminate; normal scope-exit throws propagate

**Answer (B):** std::terminate() is called because user-declared destructors are implicitly noexcept(true)

**Why:** Since C++11 ([class.dtor] / [except.spec]), a destructor with no explicit exception specification inherits the exception specification of an implicitly declared destructor—which is `noexcept(true)` unless a base or member destructor can throw. Exiting it via exception calls std::terminate().

### Question 6 [standardese] ([depr.impldec], [class.copy.ctor])

Suppose `Wrapper` declares a custom destructor `~Wrapper() { ... }` and omits copy/move declarations. Why does copying `Wrapper` still compile today despite violating the Rule of Five?

```cpp
struct Wrapper {
    int fd = -1;
    ~Wrapper() { /* ... */ }
};
```

A. Implicit copy operations are forbidden; copying Wrapper only works via memcpy
B. Move operations are still generated instead of copy operations
C. User-declared destructors only suppress special members if virtual
D. Implicit generation of copy constructor and copy assignment is deprecated when a user-declared destructor exists, though still permitted for backward compatibility

**Answer (D):** Implicit generation of copy constructor and copy assignment is deprecated when a user-declared destructor exists, though still permitted for backward compatibility

**Why:** Under [depr.impldec] and [class.copy.ctor], declaring a destructor suppresses implicit move operations outright, whereas implicit copy constructor and copy assignment generation remain allowed—but explicitly deprecated.
