RAII
- C++ course
- Intermediate
- Lesson 86/116
- 5 min
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.
Practice 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.
Starter code
#include <iostream>
// Define the Logger class here
int main() {
{
// Create a Logger (inside a scope)
}
return 0;
}Sample solution
#include <iostream>
class Logger {
public:
Logger() { std::cout << "opening"; }
~Logger() { std::cout << " closing"; }
};
int main() {
{
Logger log;
}
return 0;
}Expected output
opening closing
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
Constructor |
Acquire resource |
Destructor |
Release resource |
Scope end |
Destructor runs |
unique_ptr |
RAII example |
2 What does RAII stand for?
// modern C++ resource management pattern- Random Access Integer Index
- Recursive Algorithm Implementation
- Rapid Application Integration
- Resource Acquisition Is Initialization Correct answer
Explanation: RAII stands for Resource Acquisition Is Initialization.
3 Define the destructor
class Logger {
public:
Logger() { std::cout << "opening"; }
____Logger() { std::cout << " closing"; }
};
class Logger {
public:
Logger() { std::cout << "opening"; }
~Logger() { std::cout << " closing"; }
};
Explanation: Write ~: ~Logger() defines a destructor.