Boost logo

Boost :

Subject: Re: [boost] Proposed new RAII Library
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2012-09-12 13:48:55

On Sep 12, 2012 8:06 PM, "Andrew Sandoval" <sandoval_at_[hidden]>
> I'd like to propose a new Boost library for RAII wrapper classes that
> I think could be standardized to help promote the use of RAII. Though
> shared_ptr, scoped_ptr, etc. greatly enhance the use of RAII, I
> propose two additional classes.
> The first of these is RAIIFunction


I remember proposing something like this a few years back. My proposal was
not based on boost:: or std::function for efficiency reasons. It used
capturing the scope guard object by reference to a base class. The general
idea is shown in the end of my post. I think, performance is a critical
factor for tools like this.

Also, have you looked at Boost.ScopeExit? It provides same functionality.

> The other one I call just RAIIWrapper


I can't say I like the macro but the general idea looks interesting. I
think the reference to base class trick can be used to hide the deleter

Below is a code snippet (incomplete) illustrating the general idea I have.

struct scope_guard_base
  scope_guard_base() : active(true) {}

  bool active;

template< typename F, typename Base = scope_guard_base >
struct scope_guard_impl : Base
    if (this->active) m_fun();

  F m_fun;

typedef scope_guard_base const& scope_guard;

template< typename F >
scope_guard_impl< F > make_scope_guard(F fun)
  return scope_guard_impl< F >(fun);

template< typename T >
struct raii : scope_guard_base
  T const& get() const { return m_obj; }

  T m_obj;

template< typename T, typename F >
scope_guard_impl< F, raii< T > > make_raii(T obj, F fun)
  return scope_guard_impl< F, raii< T > >(fun, obj);

int main()
  scope_guard guard = make_scope_guard(...);
  raii< HANDLE > const& handle =
    make_raii(CreateHandle(...), bind(CloseHandle, _1));

With a little more work CloseHandle can be specified without bind (i.e. if
you detect that the function accepts a single argument of type T).

Boost list run by bdawes at, gregod at, cpdaniel at, john at