|
Boost : |
From: Marc-Antoine Ruel (maruel_at_[hidden])
Date: 2003-12-17 12:11:35
What do you think of that? I'm not very up to date with design patterns but I found that use quite interessing. It is somewhat the inverse of RIIA (resource-initialization-is-acquisition).
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/construct.hpp>
#include <boost/lambda/bind.hpp>
using namespace boost::lambda;
#include <boost/type_traits.hpp>
#include <boost/function.hpp>
// Add a function call on return of the function
struct OnReturn
{
typedef boost::function< void(void) > FnPtr;
OnReturn(FnPtr A) : m_C(A) { }
~OnReturn() { m_C(); }
FnPtr m_C;
};
and for example:
bool Foo()
{
FILE *stream;
stream = fopen( "data", "r" );
if ( !stream )
return false;
OnReturn Q1( bind(fclose, stream) );
(code that uses stream)
return true;
}
As a side-effect, It adds exception safety as the function is called during stack-unwinding, which is especially cool when using asynchronous exception handling. And the objects are destroyed in the reverse order that they have been created.
I've looked at the code bloat generated in release build and it seems relativelly big. There is some function calls as they are not all inlined (about half of debug build on MSVC7.1) and there is a new/delete added, which is not negligible.
You can add as many Qx object as wanted.
Any comments / improvement or anything already existing ?
Marc-Antoine Ruel, ing. jr.
Cardinal Health Canada
330 St-Vallier Est, Suite 330
Québec (Québec) G1K 9C5
(418) 872-0172 x8931
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk