RAII
Resource Acquisition Is Initialization
Master the C++ idiom that ties resource lifetime to object lifetime, eliminating leaks and making code exception-safe by design.
What Is a Resource?
In programming, a resource is anything your program borrows from the operating system and must eventually give back. If you forget to return it, you create a leak: the system slowly runs out of that resource.
new, freed with deletefopen, closed with fcloseconnect, closed with closeThe Manual Management Problem
When programmers manage resources by hand, three things go wrong: they forget to release, they release too early, or an exception skips the release code entirely.
Defining RAII
RAII stands for Resource Acquisition Is Initialization. It is a C++ design idiom where you tie the lifetime of a resource to the lifetime of an object:
Scope and Object Lifetime
In C++, every local variable lives inside a scope (a pair of curly braces). When execution exits that scope, every object declared inside it is destroyed in reverse order.
The Core RAII Principle
This principle eliminates the entire category of resource-leak bugs. If the object exists, the resource is valid. If the object is gone, the resource is freed.
Why RAII Is Exception-Safe
When an exception is thrown, C++ performs stack unwinding: it destroys every local object in reverse order as it exits each scope. RAII objects release their resources during this process.
Raw vs Smart Pointers
The most common RAII wrappers in modern C++ are smart pointers. They replace raw new/delete calls with objects that automatically manage heap memory.
| Raw Pointer | Smart Pointer (RAII) | |
|---|---|---|
| Allocation | int* p = new int(42); |
auto p = make_unique<int>(42); |
| Cleanup | Manual: delete p; | Automatic: destructor |
| Exception-safe? | No | Yes |
| Leak risk | High | Zero |
How to Apply RAII
unique_ptr, shared_ptr, lock_guard, fstream before writing your own.Example 1: A Simple RAII Wrapper
Example 2: std::unique_ptr
The standard library already provides RAII wrappers. std::unique_ptr is the most common: it exclusively owns a heap object and deletes it when destroyed.
Example 3: std::lock_guard
RAII isn't just for memory. A lock_guard acquires a mutex lock in its constructor and releases it in its destructor: no chance of forgetting to unlock.
RAII in the Standard Library
You don't need to write your own RAII classes for most situations. The C++ standard library is built on RAII:
The Rule of Five (and Zero)
When writing your own RAII class, you must consider copying and moving. If you define a destructor, you likely need all five special member functions:
Common Mistakes with RAII
new and delete instead of smart pointers. One missed delete = memory leak.noexcept.RAII vs Other Approaches
| RAII (C++) | Garbage Collection (Java) | Manual (C) | |
|---|---|---|---|
| Memory cleanup | Deterministic | Non-deterministic | Manual |
| Non-memory resources | Automatic | Manual (try-finally) | Manual |
| Exception safety | Built-in | Partial | None |
| Runtime cost | Zero | GC pauses | Zero |
| Leak risk | Very low | Memory: low, files: high | High |
Question 1 of 5
In RAII, when is a resource released?
Question 2 of 5
Which standard library type is an RAII wrapper for exclusive ownership of heap memory?
std::unique_ptr provides exclusive ownership: it cannot be copied, only moved. It has zero overhead compared to raw pointers. shared_ptr is for shared ownership, weak_ptr is a non-owning observer, and auto_ptr is deprecated.Question 3 of 5
Why must an RAII destructor never throw an exception?
std::terminate() and the program aborts. Destructors should always be noexcept.Question 4 of 5
What is the "Rule of Zero"?
string, vector, unique_ptr), the compiler-generated destructor, copy, and move operations are correct. You write zero special member functions.Question 5 of 5
Consider this code. What happens if doWork() throws an exception?
void process() {
auto data = std::make_unique<int[]>(100);
std::lock_guard<std::mutex> lock(mtx);
doWork(data.get()); // throws!
}
unique_ptr and lock_guard are RAII types. During stack unwinding, their destructors run in reverse order: the lock_guard destructor unlocks the mutex, then the unique_ptr destructor frees the array. No leaks, no deadlocks.