1// raii.cpp
2
3#include <iostream>
4#include <new>
5#include <string>
6
7class ResourceGuard{
8 private:
9 const std::string resource;
10 public:
11 ResourceGuard(const std::string& res):resource(res){
12 std::cout << "Acquire the " << resource << "." << std::endl;
13 }
14 ~ResourceGuard(){
15 std::cout << "Release the "<< resource << "." << std::endl;
16 }
17};
18
19int main(){
20
21 std::cout << std::endl;
22
23 ResourceGuard resGuard1{"memoryBlock1"};
24
25 std::cout << "\nBefore local scope" << std::endl;
26 {
27 ResourceGuard resGuard2{"memoryBlock2"};
28 }
29 std::cout << "After local scope" << std::endl;
30
31 std::cout << std::endl;
32
33
34 std::cout << "\nBefore try-catch block" << std::endl;
35 try{
36 ResourceGuard resGuard3{"memoryBlock3"};
37 throw std::bad_alloc();
38 }
39 catch (std::bad_alloc& e){
40 std::cout << e.what();
41 }
42 std::cout << "\nAfter try-catch block" << std::endl;
43
44 std::cout << std::endl;
45
46}
47