|
Boost : |
From: Jonathan Turkanis (technews_at_[hidden])
Date: 2005-05-01 16:06:22
Jason Hise wrote:
> Does a utility like the following already exist in boost? If so, what
> is it called? If not, is there interest in adding it?
>
> template < typename Function >
> struct free_on_error
> {
> private:
> Function function_;
> bool reset_;
>
> public:
> free_on_error ( Function function ) :
> function_ ( function ),
> reset_ ( true )
> {
> }
>
> ~ free_on_error ( )
> {
> if ( reset_ )
> {
> function_ ( );
> }
> }
>
> void discard ( )
> {
> reset_ = false;
> }
> };
>
> This would be used to make certain operations exception safe. For
> example:
>
> A * foo ( )
> {
> A * a = new A ( );
> free_on_error < BOOST_TYPEOF ( lambda::bind ( delete _1, a ) ) >
> release ( lambda::bind ( delete _1, a ) );
> a->DoSomethingThatMightThrow ( );
> release.discard ( );
> return a;
> }
It sounds like you may be looking for Petru and Andrei's ScopeGuard:
http://tinyurl.com/26vzp. (BTW, has anyone noticed http://www.scopeguard.com/ ?)
It uses a neat trick to avoid specifying the return type of bind or lambda
expressions. A version of ScopeGuard exists as an implementation detail of
multi_index. Previously, I had used a ScopeGuard in iostreams, and was planning
to move it to boost/detail. Unfortunately it caused problems with borland 5.x,
Metrowerks 8.3 and VC6, so I excised it.
Jonathan
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk