C++ RAII
RAII means:
Series navigation: Previous: Destructor and cleanup | Next: Constructor series
Resource Acquisition Is Initialization
The idea:
- acquire the resource in the constructor
- release the resource in the destructor
- let object lifetime control cleanup
RAII is one of the most important C++ ideas.
Resource
A resource is something that must be released.
Examples:
- heap memory
- file handle
- socket
- mutex lock
- database connection
- hardware handle
Basic idea
Without RAII:
The problem:
If do_work() returns early or throws an exception, close_resource() may not
run.
With RAII:
When the scope ends, the destructor runs automatically.
This happens for:
- normal scope exit
return- exception
Simple RAII class
Output:
File example
This class opens a file in the constructor and closes it in the destructor.
File cannot be copied because two objects closing the same FILE* would be
dangerous.
That is why copy is disabled:
Smart pointers are RAII
std::unique_ptr is RAII for heap memory.
When robot goes out of scope, it automatically deletes the heap object.
No manual delete is needed.
Locks are RAII
std::lock_guard is RAII for mutex locks.
The constructor locks the mutex.
The destructor unlocks the mutex.
RAII and exceptions
RAII is useful because destructors run during stack unwinding.
Even when an exception is thrown, file is destroyed before leaving run().
The destructor closes the file.
Rule of thumb
- Put resource acquisition in the constructor.
- Put resource release in the destructor.
- Do not manually call cleanup everywhere.
- Prefer standard RAII types like
std::string,std::vector,std::unique_ptr, andstd::lock_guard. - If your class owns a raw resource, think about copy, move, and destructor behavior.
Run online
Copy the simple RAII class example and run it in the embedded OneCompiler C++ runtime.
Other online compilers: OneCompiler | Compiler Explorer | Wandbox
Run locally
Save the file example as main.cpp:
Series navigation: Previous: Destructor and cleanup | Next: Constructor series