Boost C++ Libraries of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of boost. Click here for the latest Boost documentation.



A ScopeExit declaration has the following synopsis:

#include <boost/scope_exit.hpp>

BOOST_SCOPE_EXIT ( scope-exit-capture-list )


    ( scope-exit-capture )
    scope-exit-capture-list ( scope-exit-capture )


The ScopeExit declaration schedules an execution of scope-exit-body at the end of the current scope. The scope-exit-body statements are executed in the reverse order of ScopeExit declarations in the given scope. The scope must be local.

Each identifier in scope-exit-capture-list must be a valid name in enclosing scope and it must appear exactly once in the list. If a scope-exit-capture starts with the ampersand sign &, the corresponding identifier will be available inside scope-exit-body; otherwise, a copy of it will be made at the point of ScopeExit declaration and that copy will be available inside scope-exit-body. In the latter case, the idenitifer must be CopyConstructible.

Only identifiers listed in scope-exit-capture-list, static variables, extern variables and functions, and enumerations from the enclosing scope can be used inside the scope-exit-body.

[Note] Note

this pointer is not an identifier and cannot be passed to scope-exit-capture-list.

The ScopeExit uses Boost.Typeof to determine types of scope-exit-capture-list elements. In order to compile code in typeof emulation mode, all types should be registered with BOOST_TYPEOF_REGISTER_TYPE or BOOST_TYPEOF_REGISTER_TEMPLATE macros, or appropriate Boost.Typeof headers should be included.


This macro is a workaround for various versions of gcc. These compilers don't compile ScopeExit declaration inside function templates. As a workaround, the _TPL suffix should be appended to BOOST_SCOPE_EXIT.

The problem boils down to the following code:

template<class T> void foo(T const& t) {
    int i = 0;
    struct Local {
        typedef __typeof__(i) typeof_i;
        typedef __typeof__(t) typeof_t;
    typedef Local::typeof_i i_type;
    typedef Local::typeof_t t_type;

int main() { foo(0); }

This can be fixed by adding typename in front of Local::typeof_i and Local::typeof_t.

See also GCC bug 37920.

[Note] Note

Although BOOST_SCOPE_EXIT_TPL has the same suffix as the BOOST_TYPEOF_TPL, it doesn't follow a convention of the Boost.Typeof.