Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdexcept>
- using namespace std;
- class resource
- {
- public:
- resource(const string & resource_name_)
- : _resource_name(resource_name_)
- {
- cout << "resource::resource()" << endl;
- cout << "acquired resource: "
- << _resource_name << endl;
- }
- ~resource()
- {
- cout << "resource::~resource()" << endl;
- cout << "releasing resource: "
- << _resource_name << endl;
- }
- private:
- string _resource_name;
- };
- class raii_test
- {
- public:
- raii_test()
- : _rt("resource_1") {};
- void f1()
- {
- resource local_resource("resource_2");
- cout << "raii_test::f1()" <<endl;
- f2();
- }
- void f2()
- {
- cout << "raii_test::f2()" << endl;
- cout << "Throwing" << endl;
- throw runtime_error("Timepass");
- }
- void operator()()
- {
- cout << "In raii_test::operator()" << endl;
- f1();
- }
- ~raii_test()
- {
- cout << "raii_test::~raii_test" << endl;
- }
- private:
- resource _rt;
- };
- int
- main()
- {
- // try
- {
- raii_test obj;
- obj();
- }
- // catch (...)
- // {
- // throw;
- // }
- }
- -----
- Uncommenting the commented-out code causes RAII-enabled resource deallocation to work correctly. Here are the outputs with commented and uncommented code that show that:
- Output with commented-out code:
- main()
- resource::resource()
- acquired resource: resource_1
- In raii_test::operator()
- raii_test::f1()
- resource::resource()
- acquired resource: resource_2
- raii_test::f2()
- Throwing
- terminate called after throwing an instance of 'std::runtime_error'
- what(): foo bar baz
- Aborted
- Output without commented code. Note the correct deallocation/release of acquired resources:
- main()
- resource::resource()
- acquired resource: resource_1
- In raii_test::operator()
- raii_test::f1()
- resource::resource()
- acquired resource: resource_2
- raii_test::f2()
- Throwing
- resource::~resource()
- releasing resource: resource_2
- raii_test::~raii_test
- resource::~resource()
- releasing resource: resource_1
- terminate called after throwing an instance of 'std::runtime_error'
- what(): foo bar baz
- Aborted
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement