Rule:
- Acquire the resource in the constructor
- Release the resource in the destructor
When the object comes into scope, the resource is acquired.
When the object leaves scope, the resource is _guaranteed_ to be released.
Why RAII Exists (the real problem it solves)
Without RAII (manual cleanup → bugs)
void process() {
FILE* f = fopen("data.txt", "r");
if (!f) return;
if (error_happens()) {
fclose(f); // easy to forget
return;
}
fclose(f);
}
Problems:
- Multiple exit paths
- Easy to forget cleanup
- Not exception-safe
- Leaks appear under pressure
With RAII (automatic, exception-safe)
void process() {
std::ifstream f("data.txt"); // constructor opens file
if (!f) return;
// use file
} // destructor closes file automatically
Why this is better
- Cleanup is guaranteed
- Works even with
return,break, or exceptions - No duplication
- No human memory required
What Counts as a “Resource”?
RAII is not about memory only.
| Resource Type | Examples |
|---|---|
| Memory | heap buffers, arrays |
| OS handles | files, sockets |
| Sync | mutexes, locks |
| Hardware | GPU buffers, DMA |
| Ownership | pointers, handles |
If something must be released, it belongs in RAII.
How RAII Works
- Object is constructed → resource acquired
- Scope ends → destructor runs
- Resource is released deterministically
No garbage collector.
No runtime guesswork.
Purely compile-time guarantees.
Minimal RAII Example (memory)
struct Buffer {
int* data;
Buffer(size_t n) {
data = new int[n]; // acquire
}
~Buffer() {
delete[] data; // release
}
};
void work() {
Buffer b(1024);
} // memory freed automatically here
Even if:
returnhappens early- an exception is thrown
The destructor always runs.
RAII vs Garbage Collection (important distinction)
| RAII (C++) | GC (Java, Python) |
|---|---|
| Deterministic | Non-deterministic |
| Scope-based | Heap-based |
| Compile-time | Runtime |
| Real-time safe | Often not |
| Zero overhead | Runtime overhead |
This is why RAII is mandatory in:
- Embedded systems
- Real-time systems
- High-performance C++
- Game engines
- OS kernels
Why RAII Is the Foundation of Modern C++
Modern C++ is _built_ on RAII:
std::vectorstd::stringstd::unique_ptrstd::lock_guardstd::thread
None of these require you to manually free resources.