问题
I have noticed that many Poco classes have a protected destructor. This makes them more annoying to code with. For example here is some of my code:
struct W2: Poco::Util::WinRegistryConfiguration
{
typedef Poco::Util::WinRegistryConfiguration inherited;
using inherited::inherited;
};
std::string get_documents_folder()
{
W2 regc { "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders" };
return regc.getString("Personal", "");
}
Of course, it would be much simpler if I could do away with W2
and just make regc
have type WinRegistryConfiguration
. But that is not possible because of the protected destructor.
I realize it is possible to use Poco::AutoPtr
instead , but then resource is wasted by doing a dynamic allocation with new
when automatic allocation should work fine.
My question is: what is the rationale for this and am I overlooking anything?
回答1:
As answered already, Poco::RefCountedObject has protected destructor, so all classes inheriting from it can not be created on the stack. The reason is because they delete themselves when reference count reaches zero, so creating them on stack would cause undefined behavior - they are primarily meant to be used with Poco::AutoPtr, but that is not mandatory - you can also reference count manually, using duplicate() and release().
Looking at your code, you are probably looking for WinRegistryKey, which you can use like this:
std::string get_documents_folder()
{
Poco::Util::WinRegistryKey regKey("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
return regKey.getString("Personal", "");
}
回答2:
The reason is that WinRegistryConfiguration is reference-counted (inheriting from Poco::RefCountedObject). The protected destructor is meant to prevent clients from instantiating the class on the stack, or directly deleting the object. Instead, you should instantiate the class via new
, and manage the lifetime through the RefCountedObject methods.
I'm not familiar with Poco, but there should also be a smart pointer class that manages reference-counted objects by automatically calling the RefCountedObject methods.
来源:https://stackoverflow.com/questions/31508028/rationale-for-protected-destructor