RegCloseKey call on a predefined registry key handle
Consider the case wrapper class C ++ around raw HKEY
.
The wrapper class has a constructor overload using a descriptor HKEY
as input: the constructed object takes over the raw input descriptor.
The destructor is called RegCloseKey()
on the wrapped handle stored in the data item HKEY m_hKey
.
Now consider the case where a predefined type descriptor is HKEY_CURRENT_USER
passed to a constructor overload. The value is HKEY_CURRENT_USER
assigned a member m_hKey
.
The destructor calls RegCloseKey()
on this predefined key. In my experiments, the API returns 0 in this case, which means: success. So, is it ok to call RegCloseKey()
on predefined registry key handles? Or an additional check should be done, for example:
RegistryKey::~RegistryKey()
{
if ((m_hKey != nullptr) && !IsPredefinedKey(m_hKey))
::RegCloseKey(m_hKey);
}
source to share
The MSDN doc for the RegOpenKey
function states that you only want to call RegCloseKey
on a handle that you have programmatically created.
... If the key is not one of the predefined registry keys, call the function RegCloseKey
after you finish using the handle.
source to share
I can't find any official documentation that says it's ok, but I know it works.
The closest I got this book :
In fact, you can call RegCloseKey on one of the predefined entries in the root key.
Probably a lot happens in the wild, so I can't imagine Microsoft will change this in the future, but without official documentation, it's really up to you if you want to take the risk or not.
source to share