#include <iostream>
#include <cstdlib>
using namespace std;

    typedef int HANDLE;

    void DeleteHandle(HANDLE h)
    {
        cout << "deleting handle " << h << endl;
    }

    template <class H>
    class UniqueHandle {
        H h;

    public:
        UniqueHandle(H _h = 0)
            :h(_h) {}

        UniqueHandle(const UniqueHandle &other)
            :h(const_cast<UniqueHandle&>(other).YieldOwnership()) {}

        ~UniqueHandle() { ::DeleteHandle(h); }

        UniqueHandle &operator =(const UniqueHandle &other)
        {
            this->~UniqueHandle(); // release the old handle
            h = const_cast<UniqueHandle&>(other).YieldOwnership();
            return *this;
        }

        UniqueHandle &operator =(H _h)
        {
            this->~UniqueHandle(); // release the old handle
            h = _h;
            return *this;
        }

        H YieldOwnership() { H result = h; h = 0; return result; }

        operator H() const { return h; }
    };

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;
}