//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};
cout << "inside fun\n";
BOOST_SCOPE_EXIT(&a)
{
*a = 20;
delete a;
cout << "in BOOST_SCOPE_EXIT\n";
}BOOST_SCOPE_EXIT_END
cout << "outside BOOST_SCOPE_EXIT\n";
return a;
}
int main()
{
int *j = fun();
cout << j;
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;
project()
{
BOOST_SCOPE_EXIT(this_)
{
this_->a = 20;
cout << "last\n";
}BOOST_SCOPE_EXIT_END
BOOST_SCOPE_EXIT(this_)
{
this_->a = 10;
cout << "first\n";
}BOOST_SCOPE_EXIT_END
cout << "in constructor\n";
}
~project()
{
cout << "in destructor\n";
}
};
int main()
{
project pro;
cout << pro.a<<endl;
return 0;
}
Output:-
in constructor
first
last
20
in destructor
Comments