Consider the case of a C++ wrapper class around raw HKEY
handles.
The wrapper class has a constructor overload taking a HKEY
handle as input: the constructed object takes ownership of the input raw handle.
The destructor invokes RegCloseKey()
on the wrapped handle, stored in a HKEY m_hKey
data member.
Now, consider the case in which a predefined handle like HKEY_CURRENT_USER
is passed to the constructor overload. The HKEY_CURRENT_USER
value is assigned to the m_hKey
member.
The destructor calls RegCloseKey()
on that predefined key. In my experiments the API returns 0 in this case, meaning: success. So, is it fine to call RegCloseKey()
on predefined registry key handles?
Or should a further check be implemented, like:
RegistryKey::~RegistryKey()
{
if ((m_hKey != nullptr) && !IsPredefinedKey(m_hKey))
::RegCloseKey(m_hKey);
}
The MSDN doc for the RegOpenKey
function infers that you would only want to call RegCloseKey
on a handle which you've programmatically created.
...If the key is not one of the predefined registry keys, call the RegCloseKey
function after you have finished using the handle.