capypad
0 Tage Serie
cpp / intermediate
Snippet

RAII und Ausnahmesicherheit

Resource Acquisition Is Initialization (RAII) ist ein zentrales C++-Konzept. Ressourcen sind an die Lebensdauer von Objekten gebunden; sie werden im Konstruktor angefordert und im Destruktor freigegeben, was Lecks selbst bei Ausnahmen verhindert.

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
Erklärung
1
std::lock_guard<std::mutex> lock(mtx);
Sperrt den Mutex sofort. Das 'lock'-Objekt verwaltet den Zustand des Mutex, bis es den Gültigkeitsbereich verlässt.
2
throw std::runtime_error
Falls eine Ausnahme ausgelöst wird, stellt das 'Stack Unwinding' sicher, dass der Destruktor von lock_guard trotzdem aufgerufen wird.