Boost logo

Boost :

From: Jonathan Turkanis (technews_at_[hidden])
Date: 2004-07-08 11:55:26


Hi All,

    I've uploaded a very simple version of Andrei and Petru's
ScopeGuard to the files section:
http://groups.yahoo.com/group/boost/files/scope_guard.zip.

    It's only smart enough to handle cleanup functions or function
objects with the signature 'void f()'; more complex cleanup is easy
with Bind or Lambda.

There are two object generators:
  - make_guard returns a scope guard which propagates exceptions
  - safe_guard returns a scope guard which catches and ignores
exceptions

Similarly, there are two macros
  - BOOST_SCOPE_GUARD declares an anonymous scope guard which
propagates exceptions
  - BOOST_SAFE_GUARD declares an anonymous scope guard which catches
and ignores exceptions

Best Regards,
Jonathan

//------------------Example--------------------//

#include <iostream>
#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/scope_guard.hpp>

void goodbye() { std::cout << "goodbye\n"; }

void crash() { throw 0; }

struct T {
    void goodbye() { std::cout << "goodbye\n"; }
};

//
// Expected output:
// hello
// goodbye
// goodbye
// goodbye
// goodbye
// goodbye
//
int main()
{
    using namespace boost;

    T t;

    // Scope guard which invokes t.goodbye().
    scope_guard g1 = make_guard(boost::bind(&T::goodbye, t));

    // Scope guard which invokes goodbye().
    scope_guard g2 = make_guard(goodbye);

    // Scope guard which executes std::cout << "goodbye\n".
    scope_guard g3 =
        make_guard(
            std::cout << boost::lambda::constant("goodbye\n")
        );

    // Scope guard which invokes crash() in a try-catch block.
    scope_guard g4 = safe_guard(crash);

    // Scope guard which invokes crash().
    scope_guard g5 = make_guard(crash);
    g5.dismiss();

    // Scope guard which invokes goodbye().
    BOOST_SCOPE_GUARD(goodbye);

    // Same. (Shows that generated variable names are working.)
    BOOST_SCOPE_GUARD(goodbye);

    // Scope guard which invokes crash() in a try-catch block.
    BOOST_SAFE_GUARD(crash);

    std::cout << "hello\n";
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk