Hi,
Recently I've tried to implement Andrei's ScopeGuard (see http://www.cuj.com/experts/1812/alexandr.htm?topic=experts for details) with boost.function and boost.bind. Is there anything wrong with it? Thanks for reviewing.
#include
#include
#include
#define ON_BLOCK_EXIT(x) scoped_guard guard##__LINE__(::boost::bind##x)
class scoped_guard: ::boost::noncopyable
{
private:
typedef const ::boost::function<void> f_type;
// reference might cause crash
bool dismissed_;
f_type f_;
public:
scoped_guard(f_type& v): f_(v), dismissed_(false) {}
~scoped_guard() throw()
{
if(!dismissed_)
try {f_();}
catch(...) {}
}
void dismiss() throw() { dismissed_ = true; }
};
With the macro ON_BLOCK_EXIT, we can easily use it like this:
// ...
#include
int main()
{
FILE* fp = fopen("hello.txt", "r");
ON_BLOCK_EXIT((fclose, fp));
//scoped_guard guard(boost::bind(fclose, fp));
return 0;
}
Jon Wang
babysloth@c-view.org
2002-07-03