I'm writing some managed handle container, not unsimilar to std::unique_pointer
(although I'm not writing my code in C++11 yet). I have something like this:
template <class H>
class UniqueHandle {
H h;
public:
UniqueHandle(H _h = 0) // "the first constructor", referred below
:h(_h) {}
UniqueHandle(UniqueHandle &other)
:h(other.YieldOwnership()) {}
~UniqueHandle() { ::DeleteHandle(h); }
UniqueHandle &operator =(UniqueHandle &other)
{
::DeleteHandle(h); // release the old handle
h = other.YieldOwnership();
return *this;
}
UniqueHandle &operator =(H _h)
{
::DeleteHandle(h); // release the old handle
h = _h;
return *this;
}
H YieldOwnership() { H result = h; h = 0; return result; }
operator H() const { return h; }
};
There could be a bunch of other operators, but let's keep it simple. Now let's assume:
typedef int HANDLE;
void DeleteHandle(HANDLE h)
{
cout << "deleting handle " << h << endl;
}
int main()
{
UniqueHandle<HANDLE> h(123);
UniqueHandle<HANDLE> h2 = 456;
HANDLE unmanaged = 789;
HANDLE mixed_case = (rand() & 1)? (HANDLE)h : unmanaged;
DeleteHandle(unmanaged);
return 0;
}
I've tried running this on ideone, and it works as expected. However, in Visual Studio (2008), the mixed_case
does not require the conversion of h
to bare HANDLE
and instead implicitly converts unmanaged
to UniqueHandle<HANDLE>
, which causes its deletion shortly after. It took me some time to find this bug, and I know it can be fixed by declaring the first constructor as explicit
.
My question is: are the operator =
equally dangerous? What other perils one can run into with these types of unique resource managers?