Win API Handle Shell Class

Writing a wrapper class for a descriptor that receives only a value is relatively simple. I am trying to determine how best to encapsulate the descriptors that need to be passed to the address.

For example, writing a shell for something like SC_HANDLE , which is passed by the value of QueryServiceConfig () , is not so difficult. You can either implement a member function as .GetHandle () , or implement operator () .

The problem (at least for me) is API functions like RegOpenKeyEx () , which wants an HKEY address.

I read that operator overloads are usually a bad idea. What is the recommended way to preserve encapsulation (or as much as possible) and especially resource collection, while accessing the API functions?

+7
source share
1 answer

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.

+2
source

All Articles