File tree 1 file changed +10
-6
lines changed
1 file changed +10
-6
lines changed Original file line number Diff line number Diff line change @@ -600,25 +600,29 @@ It is possible to use scope guard classes to implement scope exit actions that a
600
600
a function object wrapper such as `std::function` together with the scope guard to schedule the function call. For example:
601
601
602
602
using cleanup_func_t = std::function< void() >;
603
+ cleanup_func_t cleanup_func;
603
604
// Create an inactive scope guard first, since the cleanup function is not set yet
604
- boost::scope::scope_exit< cleanup_func_t > cleanup(cleanup_func_t() , false);
605
+ boost::scope::scope_exit< cleanup_func_t& > cleanup(cleanup_func , false);
605
606
606
- // Later in the program, initialize the scope guard with the function selected at run time
607
+ // Later in the program, initialize the cleanup function with the function selected at run time
607
608
if (cond)
608
609
{
609
- cleanup = boost::scope::scope_exit< cleanup_func_t >( []
610
+ cleanup_func = []
610
611
{
611
612
std::cout << "cond is true" << std::endl;
612
- }) ;
613
+ };
613
614
}
614
615
else
615
616
{
616
- cleanup = boost::scope::scope_exit< cleanup_func_t >( []
617
+ cleanup_func = []
617
618
{
618
619
std::cout << "cond is false" << std::endl;
619
- }) ;
620
+ };
620
621
}
621
622
623
+ // Activate the scope guard once the cleanup function is initialized
624
+ cleanup.set_active(true);
625
+
622
626
It is also possible to do this with `BOOST_SCOPE_DEFER`, although it eliminates one of the advantages provided by this macro, namely not
623
627
having to invent a variable name. Also note that the function wrapper must be valid at all times once the scope guard is constructed.
624
628
You can’t perform that action at this time.
0 commit comments