You can always add another layer of indirection to avoid the terrible overload of operator& and the ugly Attach or Detach and return a pre-packaged instance from there.
If you can use C ++ 0x in VS2010 or gcc or have other ways to access std::unique_ptr<> , you can do this (error checking is 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); ... }
hkey_deleter will verify that the registry key closes when the region exits or regkey::reset() called.
Johann Gerell
source share