Skip to content

Lesson 1 of 9 · 24m

RAII: Lifetimes Are the Program

Treat constructors and destructors as the resource-management mechanism, not as syntax trivia, and design objects whose lifetimes make cleanup automatic.

The worst production outage I ever inherited from a C++ service was not caused by a missing delete. It was caused by a socket that was closed in the success path, leaked in one error path, and closed twice in another. Three programmers had each fixed one branch. RAII exists because humans are reliably bad at pairing operations across branches, exceptions, early returns, and refactors.

The mental model

In C++, object lifetime is a language feature with teeth. When an automatic object goes out of scope, its destructor runs — even when control leaves through an exception. Use that guarantee deliberately:

void process(int fd) {
    File file(fd);              // owns fd now
    auto header = read_header(file);
    if (header.empty()) {
        return;                 // destructor closes fd
    }
    write_response(file);       // may throw; fd is still closed
}                               // destructor runs here

The resource policy is now attached to the object, not distributed across every caller. That is the core move. Do not remember cleanup; make cleanup impossible to forget.

Write small resource owners

The standard library already owns memory, files, mutexes, threads, and more. When you have a C API or OS handle, write a narrow owner once:

class File {
public:
    explicit File(int fd) noexcept : fd_(fd) {}
    ~File() { if (fd_ >= 0) ::close(fd_); }

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

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

    int get() const noexcept { return fd_; }

private:
    int fd_ = -1;
};

Notice the details: noncopyable because copying ownership would be ambiguous, movable because transferring ownership is useful, and tolerant of an empty moved-from state. This is not boilerplate worship. It is the price of making close happen exactly once.

RAII is ordering control too

Destruction runs in reverse construction order. That is how you express dependencies: construct the logger before the worker, the worker before the monitoring hook. If shutdown order matters, put the objects in a scope in the order you mean. Do not encode shutdown as a comment.

std::lock_guard lock(mutex);       // unlocks at scope exit
Transaction tx(db);                // commits or rolls back deterministically
TempDirectory scratch;             // removes files even on failure

Failure modes senior engineers watch for

RAII fails when destructors perform operations that can throw, when objects secretly share ownership, or when a class both implements business logic and manually owns five unrelated resources. Destructors should be noexcept. Complex workflows should use explicit commit methods, while destructors provide safe rollback.

Field notes

  • Never call close(fd) in a destructor and also expose a method that closes the same descriptor without resetting state.
  • std::unique_ptr, std::fstream, std::lock_guard, and std::jthread are already RAII types; use them before inventing your own.
  • Do not throw from destructors. During stack unwinding a second exception calls std::terminate.
  • If cleanup order matters, make declaration order mirror the dependency order and explain unusual cases in the type design, not at call sites.

Was this lesson helpful?

Sign in to rate