I have a C++ RAII class for managing Win32 HANDLEs using boost::shared_ptr<> that looks a bit like this:
namespace detail {
struct NoDelete { void operator()( void* ) {}; };
}; // namespace detail
template< typename HANDLE_TYPE, typename HANDLE_DELETER >
class CHandleT
{
public :
explicit CHandleT( HANDLE_TYPE handle, bool delete_on_release = true )
{
if( delete_on_release )
handle_ = Handle( handle, HANDLE_DELETER() );
else
handle_ = Handle( handle, detail::NoDelete() );
};
operator HANDLE_TYPE() const { return static_cast< HANDLE_TYPE >( handle_.get() ); };
protected:
typedef boost::shared_ptr< void > Handle;
Handle handle_;
}; // class CHandleT
struct DeallocateHandle
{
void operator()( void* handle ) { ::CloseHandle( handle ); };
};
typedef CHandleT< HANDLE, DeallocateHandle > CHandle;
I would like to extend it such that instead writing:
CHandle my_handle( ::CreateEvent( NULL, FALSE, FALSE, NULL ) );
::SetEvent( my_handle.get() );
I could write:
CEvent my_event( NULL, FALSE, FALSE, NULL );
my_event.SetEvent();
Would the best way to do that be to use the CHandle class as a member of a CEvent class?
class CEvent
{
public:
explicit CEvent( LPSECURITY_ATTRIBUTES lpEventAttributes = NULL,
BOOL bManualReset = TRUE,
BOOL bInitialState = FALSE,
LPCTSTR lpName = NULL,
bool delete_on_release = true ) :
handle_( new CHandle( ::CreateEvent( lpEventAttributes,
bManualReset,
bInitialState,
lpName ),
delete_on_release ) )
{
};
BOOL SetEvent()
{
_ASSERT( NULL != handle_ && NULL != handle_.get() );
return ::SetEvent( handle_.get() );
};
private:
boost::shared_ptr< CHandle > handle_;
}; // class CEvent
Or, is there a better way? (Note that I still want to maintain the copy semantics of the CHandle given by boost::shared_ptr<>.
Thanks, PaulH