Win API wrapper classes for handles Win API wrapper classes for handles windows windows

Win API wrapper classes for handles


You can always add another layer of indirection to avoid the awful overloading of operator& and ugly Attach or Detach and return a pre-wrapped instance from there.

If you can use C++0x in VS2010 or gcc, or have other ways of accessing std::unique_ptr<>, then you can do this (error checking omitted for brevity):

struct hkey_deleter{    void operator()(HKEY hkey)    {        ::RegCloseKey(hkey);    }};typedef std::unique_ptr<HKEY__, hkey_deleter> regkey;regkey MyRegOpenKeyEx(HKEY hKey, LPCTSTR lpSubKey, DWORD ulOptions, REGSAM samDesired){    HKEY hOpenedKey = NULL;    ::RegOpenKeyEx(hKey, lpSubKey, ulOptions, samDesired, &hOpenedKey);    return regkey(hOpenedKey);}void SomewhereElse(){    ...    regkey r = MyRegOpenKeyEx(HKEY_CLASSES_ROOT, nullptr, 0, KEY_READ);    ...}

The hkey_deleter will make sure that the registry key gets closed when the scope is exited or regkey::reset() is called.