Chapter 3. Boost.ScopeExit

    Example 3.1. Using

    Boost.ScopeExit provides the macro BOOST_SCOPE_EXIT, which can be used to define something that looks like a local function but doesn’t have a name. However, it does have a parameter list in parentheses and a block in braces.

    The header file boost/scoped_exit.hpp must be included to use BOOST_SCOPE_EXIT.

    The parameter list for the macro contains variables from the outer scope which should be accessible in the block. The variables are passed by copy. To pass a variable by reference, it must be prefixed with an ampersand, as in Example 3.1.

    Code in the block can only access variables from the outer scope if the variables are in the parameter list.

    BOOST_SCOPE_EXIT is used to define a block that will be executed when the scope the block is defined in ends. In the block defined with BOOST_SCOPE_EXIT is executed just before foo() returns.

    Please note that the variable i is set to 0 at the end of the block defined by . _i is then returned by foo() and written to the standard output stream in main(). However, the example doesn’t display 0. j is set to a random value – namely the address where the int variable was before the memory was freed. The block behind BOOSTSCOPE_EXIT got a reference to _i and freed the memory. But since the block is executed at the end of foo(), the assignment of 0 to i is too late. The return value of foo() is a copy of i that gets created before i is set to 0.

    You can ignore Boost.ScopeExit if you use a C++11 development environment. In that case, you can use RAII without resource-specific classes with the help of lambda functions.

    Example 3.2. Boost.ScopeExit with C++11 lambda functions

    Example 3.2 defines the class scope_exit whose constructor accepts a function. This function is called by the destructor. Furthermore, a helper function, make_scope_exit(), is defined that makes it possible to instantiate scope_exit without having to specify a template parameter.

    In foo() a lambda function is passed to makescope_exit(). The lambda function looks like the block after BOOST_SCOPE_EXIT in : The dynamically allocated int variable whose address is stored in _i is freed with . Then 0 is assigned to i.

    The example does the same thing as the previous one. Not only is the int variable deleted, but j is not set to 0 either when it is written to the standard output stream.

    Example 3.3 introduces some peculiarities of BOOST_SCOPE_EXIT:

    displays first, last, and 20 in that order.

    Replace and the user-defined deleter with BOOST_SCOPE_EXIT: