capypad
0 day streak
cpp / intermediate
Snippet

RAII and Exception Safety

Resource Acquisition Is Initialization (RAII) is a core C++ idiom. Resources are tied to object lifetime; they are acquired in the constructor and released in the destructor, ensuring they are never leaked, even during exceptions.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <mutex>
 
std::mutex mtx;
 
void shared_resource_access() {
// Mutex is locked in constructor
std::lock_guard<std::mutex> lock(mtx);
// Critical section: performing work
if (/* something fails */ false) {
throw std::runtime_error("Error");
}
} // Mutex is released in destructor, even if exception occurs
Breakdown
1
std::lock_guard<std::mutex> lock(mtx);
Locks the mutex immediately. The 'lock' object manages the mutex state until it goes out of scope.
2
throw std::runtime_error
If an exception is thrown, stack unwinding ensures that the lock_guard destructor is still called.