C++ for Systems Programmers

RAII (resource acquisition is initialization)

/ R-A-I-I, say it 'rah-ee' or spell the letters /

In C, if you call open() you must remember to call close(); if you call malloc() you must remember to call free(). The trouble is the 'remember' part: an early return, a goto, or a thrown error can skip the cleanup, and you leak the resource. RAII is C++'s answer, and despite the clumsy name the idea is simple: tie the lifetime of a resource to the lifetime of a local object, so the cleanup happens automatically when that object goes out of scope.

Here is how it actually works. C++ guarantees that when a local object is destroyed, its destructor runs. So you wrap the resource in a small object: the constructor acquires it (opens the file, locks the mutex, allocates the memory), and the destructor releases it (closes, unlocks, frees). Now you never write the cleanup at the call site at all — you just create the object, and the language runs the destructor for you at the closing brace, on the normal path, on an early return, and even while an exception is unwinding the stack. The name says 'acquisition is initialization' because you grab the resource in the constructor; the more important half is that release is destruction.

RAII is the single most important idea in modern C++ and the foundation everything else here sits on: std::unique_ptr, std::shared_ptr, std::vector, std::lock_guard, and std::fstream are all RAII wrappers. The honest caveat: the destructor only runs if the object's lifetime actually ends normally — a raw new without a matching delete is not RAII, and a hard process kill or std::abort() skips destructors entirely. RAII manages resources whose cleanup you control, not every possible failure of the machine.

{ std::lock_guard<std::mutex> g(m); /* m is locked here */ } // m unlocked automatically at the closing brace, even if the body throws

The lock is released by the destructor when g leaves scope — no explicit unlock(), and no leak on the exception path.

RAII is not garbage collection: cleanup is deterministic and happens at a known point (the closing brace), not 'sometime later' when a collector decides. That predictability is exactly what makes it suitable for systems work.

Also called
scope-bound resource management資源取得即初始化