Re: Locking arbitrary resources without creating objects on the heap (longish)
ok, here is what I feel is a more generic version of Joshua Lehrer's
solution:
struct BaseLock {}; // no operator bool member
typedef const BaseLock & GenericLock;
template < typename T, typename D >
struct TransferrableRAII : public BaseLock
{
explicit TransferrableOwnership( T& t ) : m_t( t ), m_enabled( true
)
{
D::init( t );
}
~TransferrableOwnership() // not virtual for efficiency reasons,
same as BaseLock
{
if ( m_enabled )
{
D::release( t ); // or whatever name you prefer to use
}
}
TransferrableRAII( const TransferrableRAII & other )
: m_t( other.t ), m_enabled( other.enabled )
{
other.m_enabled = false;
}
private:
T& m_t;
mutable bool m_enabled;
};
You could probably have another generic function that takes member
functions or boost binders or whatever but a simple implementation for
one that has lock() and unlock() members is:
struct LockUnlock
{
template < typename T >
static init( T& t ) { t.lock(); }
template < typename T >
static release( T & t ) { t.unlock(); }
};
(You could also derive from 2 classes, one that locks and one that
unlocks).
Now to create the lock:
TransferrableOwnership< mutex, LockUnlock > make_mutex_lock( mutex & m
)
{
return TransferrableOwnership< mutex, LockUnlock >( m );
}
{
GenericLock lock( make_mutex_lock( myMutex ) );
// code that needs the mutex locked
}
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]