RAII: constructors, destructors & scope
The closing brace is the cleanup code. That is the whole idea.
Before you start
**RAII** stands for "Resource Acquisition Is Initialisation" — an unhelpful name for a very useful idea: tie every resource (memory, file, lock, socket) to the lifetime of a stack variable, so when the variable goes out of scope, its cleanup runs automatically.
The **constructor** grabs the resource; the **destructor** releases it. Because destructors fire at the closing brace, cleanup happens for you — even if the function throws an exception or returns early.
This lesson watches a File object open a file in its constructor and close it in its destructor, so you can see cleanup happen the instant the object goes out of scope.
Stack
The problem RAII solves: every early return, break, and throw is a leak waiting to happen.
Step 1 of 6. read_config() is called. A frame is pushed. Nothing has been constructed yet — `f` is a name the compiler knows about, but its constructor has not run. In C you would now write `fopen`, and mentally note that every exit path from this function must call `fclose`.
Step 01 / 06
read_config() is called
A frame is pushed. Nothing has been constructed yet — f is a name the compiler knows about, but its constructor has not run.
In C you would now write fopen, and mentally note that every exit path from this function must call fclose.
#include <cstdio>struct File { FILE *handle; File(const char *path) { // constructor: acquire handle = fopen(path, "r"); printf("opened\n"); } ~File() { // destructor: release if (handle) fclose(handle); printf("closed\n"); }};void read_config() { File f("config.txt"); if (!f.handle) return; // early return — still closed // ... use f ...} // destructor runs hereint main() { read_config(); return 0;}