|
Boost : |
From: Joe Swatosh (joe-swatosh_at_[hidden])
Date: 2002-08-29 16:04:25
> > I'd love to see scope_guard as a part of boost. What's the
> next step?
> >
> me too.
>
>
> Is there a way to get you proposal?
>
> kind regards
> Torsten
>
Not really. I removed it from the yahoo files area due to lack of interest and because the solution turns out to be so simple, since boost.bind does the heavy lifting of binding the arguments and a boost.function holds the function pointer.
It's basically the same as a scope_guard implementation posted by Jon Wang on the boost_user list (and commented on by Doug Gregor)(Near as I can tell, Jon is trying to optimize away the copy of the boost::function object. We can live with it, so we are keeping the code simple). The only substantial change was to remove the try/catch from the destructor as is now suggested by Andrei Alexandrescu (since it is simple enough to wrap your function in an "ignore_all_exceptions" wrapper if that is the behavior needed).
Actually, since it's only 40 lines, I'll paste it below. I hope it helps.
Joe Swatosh [mailto:joe-swatosh_at_[hidden]]
3305 Main St. Suite 201
Vancouver, WA 98663
360-737-6654 ext 201
-----------------------------------------------------------
#include <boost/function/function0.hpp>
class scope_guard //: private boost::noncopyable
{
public:
explicit scope_guard( const boost::function0<void>& v )
: f_(v)
, dismissed_(false)
{
}
~scope_guard() //throw()
{
if(!dismissed_)
{
f_();
}
}
void dismiss() //throw()
{
dismissed_ = true;
}
private:
bool dismissed_;
const boost::function0<void> f_;
// Disable copy and assignment - not implemented.
// Declaring them here keeps VC6 from complaining that it can't
// generate 'em
scope_guard& operator=(const scope_guard&);
scope_guard(const scope_guard&);
};
#define ANONYMOUS_VARIABLE(str) BOOST_JOIN(str, __LINE__)
#define ON_BLOCK_EXIT(F) boost::scope_guard \
ANONYMOUS_VARIABLE(anonymousScopeGuard)(F)
-----------------------------------------------------------
void trivial_examples_of_scope_guard()
{
using namespace boost;
{
ON_BLOCK_EXIT( bind( &setBool, ref(hasBeenCleanedUp) ) );
}
{
scope_guard theGuard( bind( &setBool, ref(hasBeenCleanedUp) ) );
theGuard.dismiss();
}
}
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk