C++
RAII
Learn resource management with the RAII pattern.
RAII
RAII (Resource Acquisition Is Initialization) is a pattern where resource acquisition is initialization. A resource (memory, file, socket) is acquired in an object's constructor and released in its destructor. When the object goes out of scope the destructor runs automatically.
Smart pointers are the best-known example of RAII: unique_ptr calls new in its constructor and delete in its destructor. You can write your own RAII classes too. For example a Logger class prints "opening" in its constructor and "closing" in its destructor. This pattern guarantees the resource is released even if an exception occurs; because the destructor always runs.
Scope guard
The power of RAII lies in the scope guard idea. When an object is created in a scope, at the end of the scope its destructor runs automatically. This removes the need for try/finally or manual cleanup.
Example: in { Logger log; ... } the log is created and at the block end its destructor runs. Even if an exception is thrown inside, the destructor runs; because C++ calls the destructors of all local objects during stack unwinding. This is a core mechanism of C++ for memory safety and resource management. Smart pointers, containers and STL containers all use RAII.
Exercise Write a RAII Logger class
Define a Logger class. The constructor prints std::cout << "opening";. The destructor (~Logger()) prints std::cout << " closing";. In main, create Logger log; inside a { } block; when the block ends the destructor runs.
Show example solution
#include <iostream>
class Logger {
public:
Logger() { std::cout << "opening"; }
~Logger() { std::cout << " closing"; }
};
int main() {
{
Logger log;
}
return 0;
}
Test yourself
-
Match each piece to its role
- Constructor
- Acquire resource
- Destructor
- Release resource
- Scope end
- Destructor runs
- unique_ptr
- RAII example
-
What does RAII stand for?
// modern C++ resource management pattern
- Random Access Integer Index
- Recursive Algorithm Implementation
- Rapid Application Integration
- Resource Acquisition Is Initialization
Show answer
Resource Acquisition Is Initialization — RAII stands for Resource Acquisition Is Initialization.
-
Define the destructor
class Logger {
public:
Logger() { std::cout << "opening"; }
____Logger() { std::cout << " closing"; }
};
Show answer
class Logger {
public:
Logger() { std::cout << "opening"; }
~Logger() { std::cout << " closing"; }
};
Next lesson: Summary - Smart pointers