我有一个 C++ RAII 类,用于使用 boost::shared_ptr<> 管理 Win32 HANDLE,看起来有点像这样:
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;
我想扩展它,而不是写:
CHandle my_handle( ::CreateEvent( NULL, FALSE, FALSE, NULL ) );
::SetEvent( my_handle.get() );
我可以写:
CEvent my_event( NULL, FALSE, FALSE, NULL );
my_event.SetEvent();
最好的方法是使用 CHandle 类作为 CEvent 类的成员吗?
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
或者,还有更好的方法?(请注意,我仍然想维护 boost::shared_ptr<> 给出的 CHandle 的复制语义。
谢谢,保罗