Reputation: 42924
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);
}
Upvotes: 3
Views: 662
Reputation: 101616
I cannot find official documentation that says it is OK but I know it works.
The closest I got was this book:
You can actually call RegCloseKey on one of the predefined root key entries.
It probably happens a lot in the wild so I cannot imagine that Microsoft would change this in the future but without official documentation it is really up to you if you want to risk it or not.
Upvotes: 1
Reputation: 1277
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.
Upvotes: 3