“Know how to solve every problem that has been solved.” “What I cannot create, I do not understand.” — Richard Feynman

RAII: cleanup the compiler guarantees

Learn

Lesson 3 of 7 standard ~6 min

C++ has no garbage collector, yet leaks and dangling resources are avoidable — because object lifetime is deterministic. RAII (Resource Acquisition Is Initialization) ties a resource to an object: acquire it in the constructor, release it in the destructor, and let scope rules do the rest.

It rests on knowing exactly when a destructor fires. When is that?

introMultiple choice

A local object is created on the stack inside a function. When does its destructor run?

Go deeper ↓Classes and objects

When several objects share a scope, the order of teardown is what makes layered ownership safe. Predict it.

standardPredict + reveal

Three guard objects are constructed in order. What is the destruction order at the closing brace? Predict the full output.

struct Guard {
    const char* name;
    Guard(const char* n) : name(n) { std::cout << "ctor " << name << "\n"; }
    ~Guard()                       { std::cout << "dtor " << name << "\n"; }
};

int main() {
    Guard a("A");
    Guard b("B");
    Guard c("C");
}
Go deeper ↓Classes and objects

Put it together and you get the headline benefit: code that is correct even when an exception tears through it.

standardMultiple choice

Why does wrapping a mutex lock in a stack guard (std::lock_guard) make it exception-safe, where a manual lock() / unlock() pair is not?

Go deeper ↓Classes and objects