RAII: cleanup the compiler guarantees
Learn
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?
A local object is created on the stack inside a function. When does its destructor run?
When several objects share a scope, the order of teardown is what makes layered ownership safe. Predict it.
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");
}
Put it together and you get the headline benefit: code that is correct even when an exception tears through it.
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?