| Home | Libraries | People | FAQ | More

## Chapter 1. Boost.ScopeExit 1.1.0

### Alexander Nasonov

### Lorenzo Caminiti `<lorcaminiti@gmail.com>`

Copyright © 2006-2012 Alexander Nasonov, Lorenzo Caminiti

Distributed under the Boost Software License, Version 1.0 (see accompanying file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt)

This library allows to execute arbitrary code when the enclosing scope exits.

## Introduction

Nowadays, every C++ developer is familiar with the Resource Acquisition Is Initialization (RAII) technique. It binds resource acquisition and release to initialization and destruction of a variable that holds the resource. There are times when writing a special class for such a variable is not worth the effort. This is when Boost.ScopeExit comes into play.

Programmers can put resource acquisition directly in their code and next to it, they can write code that releases the resource using this library. For example (see also `world.cpp`): [1]

    void world::add_person(person const& a_person) {
        bool commit = false;

        persons_.push_back(a_person);           // (1) direct action
        // Following block is executed when the enclosing scope exits.
        BOOST_SCOPE_EXIT(&commit, &persons_) {
            if(!commit) persons_.pop_back();    // (2) rollback action
        } BOOST_SCOPE_EXIT_END

        // ...                                  // (3) other operations

        commit = true;                          // (4) disable rollback actions
    }

[1] Older versions of this library used a Boost.Preprocessor sequence to specify the list of captured variables. While maintaining full backward compatibility, it is now possible to specify the captured variables also using a comma-separated list (which is the preferred syntax). See the No Variadic Macros section for more information.

Last revised: April 28, 2012 at 01:48:44 GMT |