C++ Boost Scope Exit














































C++ Boost Scope Exit



//implementable on C++11/14/17

Boost Scope Exit

Description:-
BOOST_SCOPE_EXIT is a macro that declares a scope exit. The execution of the scope exit body takes place at the exit of the enclosing scope which must be local. The BOOST_SCOPE_EXIT must have a parameter list in parentheses and a block in braces. If multiple scopes exits are declared within the same enclosing scope, the scope exit bodies are executed in reverse order of their declarations.
Header File Used:-
#include<boost/scope_exit.hpp>
Initialization:-
{

//scope local scope
BOOST_SCOPE_EXIT(parameter)
{

 //body code

}BOOST_SCOPE_EXIT_END


}
note:-parameter should be variable or if not then void.
Points to remember while using BOOST_SCOPE_EXIT:-
1)The end of scope exit body should be marked by BOOST_SCOPE_EXIT_END.
2)The parentheses of BOOST_SCOPE_EXIT must not be empty.
3)If no variables are passed in the BOOST_SCOPE_EXIT then it is necessary to specify void.
4)When BOOST_SCOPE_EXIT is used in a member function and if we want to pass a pointer to the current object, we must use this_, not this.
5)The variables that can be used inside BOOST_SCOPE_EXIT must be static, global or extern variables.
Implementation:-

#include <iostream> #include<boost/scope_exit.hpp> using namespace std; int *fun() { int* a = new int{10};//dynamic allocation cout << "inside fun\n"; BOOST_SCOPE_EXIT(&a)//BOOST_SCOPE_EXIT macro (note-if no variable is passed to boost scope exit then you should specify void) { *a = 20; delete a;//to free the memory occupied by a cout << "in BOOST_SCOPE_EXIT\n"; }BOOST_SCOPE_EXIT_END//macro end cout << "outside BOOST_SCOPE_EXIT\n"; return a; } int main() { int *j = fun(); cout << j;//will print the address where the int variable was before the memory was freed return 0; }

Output:-
inside fun outside BOOST_SCOPE_EXIT in BOOST_SCOPE_EXIT 000001994014F280
Program using multiple boost scope exit and demonstrating its peculiarities:-

#include <iostream> #include<boost/scope_exit.hpp> using namespace boost; using namespace std; class project //a class named project { public: int a;//data member project()//constructor { BOOST_SCOPE_EXIT(this_)//boost scope exit macro { this_->a = 20;//changing the contents of a cout << "last\n"; }BOOST_SCOPE_EXIT_END//end of the macro boost scope exit BOOST_SCOPE_EXIT(this_)//another scope exit macro { this_->a = 10;//changing the contents of a cout << "first\n"; }BOOST_SCOPE_EXIT_END//end of macro cout << "in constructor\n"; } ~project()//destructor { cout << "in destructor\n"; } }; int main() { project pro;//object of the project class cout << pro.a<<endl;//to print variable a of project class (note-it should be in public as we are directly accessing it in main) return 0; }
Output:-
in constructor first last 20 in destructor


Comments