Quiz Entry - updated: 2026.07.06
What is RAII in C++?
RAII = Resource Acquisition Is Initialization: tie a resource's lifetime to an object so its destructor releases the resource automatically.
* The constructor acquires, the destructor releases — and because the destructor runs at every scope exit (even during an exception), cleanup can't be forgotten. *
void process() {
vector<int> v; // memory acquired
v.push_back(1);
// ... use v ...
} // v goes out of scope -> destructor frees its memory automatically
void readFile() {
ifstream file("data.txt"); // file opened
// ... read from file ...
} // file closed automatically when it's destroyed
Key principle:
- Acquire the resource in the constructor
- Release it in the destructor
- The object's scope then controls the resource's lifetime
Benefits:
- No leaks — cleanup is automatic, even if you forget
- Exception-safe — destructors still run as the stack unwinds during an exception
- No scattered manual cleanup code
Tip: RAII is why smart pointers (unique_ptr, shared_ptr) are preferred over raw new/delete — they're RAII wrappers that delete for you.
Go deeper:
RAII — cppreference — the idiom defined, with standard RAII types.
Resource acquisition is initialization — Wikipedia — RAII across languages.