-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathraii_test.cpp
More file actions
36 lines (28 loc) · 828 Bytes
/
raii_test.cpp
File metadata and controls
36 lines (28 loc) · 828 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <cstdlib>
#include <mutex>
#include <exception>
std::mutex m;
bool everything_ok()
{
}
void f()
{
throw new std::bad_exception();
}
void bad()
{
m.lock(); // acquire the mutex
f(); // if f() throws an exception, the mutex is never released
if(!everything_ok()) return; // early return, the mutex is never released
m.unlock(); // if bad() reaches this statement, the mutex is released
}
void good()
{
std::lock_guard<std::mutex> lk(m); // RAII class: mutex acquisition is initialization
f(); // if f() throws an exception, the mutex is released
if(!everything_ok()) return; // early return, the mutex is released
}
int main()
{
return 1;
}