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]>
wrote:
>
> 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

[snip]

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

[snip]

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
type.

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
{
  ~scope_guard_impl()
  {
    if (this->active) m_fun();
  }

private:
  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; }

private:
  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 acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk