1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
// This is the Win32 version of this struct
#if !defined(_WIN32)
#error Win32 only header included from non-Win32 build environment
#endif
#ifndef AUTOHANDLE_H
#define AUTOHANDLE_H
// automap will auto-release mmaped areas
class autohandle {
HANDLE handle;
mutable bool owner;
public:
explicit autohandle( HANDLE handle_p=NULL ) : handle(handle_p),
owner(valid())
{
}
autohandle( const autohandle &that ) : handle(that.release()), owner(true)
{
}
~autohandle()
{
clear();
}
HANDLE get() const
{
return handle;
}
operator HANDLE() const
{
return get();
}
autohandle &operator=( const autohandle &that )
{
if( handle!=that.handle ) {
clear();
owner=that.owner;
if( owner ) {
handle=that.release();
} else {
handle=that.get();
}
}
return *this;
}
void clear()
{
if( owner ) {
CloseHandle( handle);
handle=NULL;
owner=false;
}
}
HANDLE release() const
{
#if defined(EXCEPT_CLASS)
if( !owner )
throw EXCEPT_CLASS("Releasing non-owner handle");
#endif
owner=false;
return handle;
}
bool valid() const
{
return handle!=NULL && handle!=INVALID_HANDLE_VALUE;
}
// WIN32 extensions
autohandle Duplicate(bool inheritable) const
{
HANDLE hProcess=GetCurrentProcess();
HANDLE hNewHandle=NULL;
if( !DuplicateHandle(hProcess, handle, hProcess, &hNewHandle, 0, inheritable,
DUPLICATE_SAME_ACCESS ) ) {
#if defined(EXCEPT_CLASS)
throw EXCEPT_CLASS("Error duplicating handle", GetLastError());
#endif
}
return autohandle(hNewHandle);
}
};
#endif // AUTOHANDLE_H
|