RAII as a pattern
RAII as a design pattern is the rule that every resource is owned by an object whose destructor releases it. Locks, files, sockets, and memory all follow the same shape. The language feature is destructors; the pattern is applying them to every acquire/release pair.
Detailed Explanation
The memory page on RAII explains the mechanism. The pattern is the habit: if you called open, there is an object whose destructor calls close. If you called lock, there is a guard. If you called new, there is a unique_ptr. You do not write a second cleanup path for exceptions. You do not write goto fail unless you are in a C API.
That habit is why modern C++ can use exceptions without leaking. It is why a function that allocates three resources is still readable: three declarations, then the logic. Destruction order is reverse construction order, which you use on purpose (flush a buffer before closing the file that owns it — declare the file first so it dies last).
The pattern extends past memory:
lock_guard/unique_lock/scoped_lockfstream,unique_ptr<FILE, closer>jthread(join on destroy)- A
gsl::finallyor a smallScopeExitfor one-off cleanup you do not want to name - Transaction rollback objects that commit in
release()and roll back in the destructor if not committed
A good RAII type is move-only or a well-defined value, has a non-throwing destructor, and does not offer a way to forget release (or if it does, release() is explicit and rare).
The anti-pattern is a class that has an init/shutdown pair the caller must remember, plus a destructor that also shutdowns, plus a boolean started_. That is RAII with extra failure modes. Construct ready, destroy done.
See also PIMPL: the unique_ptr<Impl> is RAII for the implementation allocation. See also unique_ptr custom deleters: RAII for C handles.
This pattern is C++'s answer to try/finally and to Go's defer. You attach cleanup to a name in a scope, not to a line you might skip.
Code Examples
#include <fstream>
#include <mutex>
#include <string>
std::mutex mu;
void writeLog(const std::string& path, const std::string& line) {
std::lock_guard<std::mutex> lock(mu);
std::ofstream out(path, std::ios::app);
out << line << '\n';
} // ofstream closes, mutex unlocks, even if << throws#include <cstdio>
#include <memory>
struct FClose {
void operator()(std::FILE* f) const { if (f) std::fclose(f); }
};
int main() {
std::unique_ptr<std::FILE, FClose> f(std::fopen("/dev/null", "r"));
return f ? 0 : 1;
}Common Gotchas
Throwing from a destructor
breaks the pattern's exception-safety story. Catch inside, or expose `close()`.
Unnamed guards
`lock_guard<mutex>(mu);` is not a critical section. Name it.
`release()` abandons the pattern
after `unique_ptr::release` you own a raw resource again. Do it only at a C API boundary.
Construction order versus dependency
if B needs A to still exist in `~B`, declare A first (destroyed last).