-
Notifications
You must be signed in to change notification settings - Fork 12
/
raii.cpp
44 lines (34 loc) · 879 Bytes
/
raii.cpp
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
37
38
39
40
41
42
43
44
#include <iostream>
#include <new>
#include <string>
class ResourceGuard{
private:
const std::string resource;
public:
ResourceGuard(const std::string& res):resource(res){
std::cout << "Acquire the " << resource << "." << '\n';
}
~ResourceGuard(){
std::cout << "Release the "<< resource << "." << '\n';
}
};
int main(){
std::cout << '\n';
ResourceGuard resGuard1{"memoryBlock1"};
std::cout << "\nBefore local scope" << '\n';
{
ResourceGuard resGuard2{"memoryBlock2"};
}
std::cout << "After local scope" << '\n';
std::cout << '\n';
std::cout << "\nBefore try-catch block" << '\n';
try{
ResourceGuard resGuard3{"memoryBlock3"};
throw std::bad_alloc();
}
catch (std::bad_alloc& e){
std::cout << e.what();
}
std::cout << "\nAfter try-catch block" << '\n';
std::cout << '\n';
}