Rationale for a protected destructor

I noticed that many Poco classes have a protected destructor. This makes them more annoying for coding. For example, here are some of my codes:

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 easier if I could do away with W2 and just make regc be of type WinRegistryConfiguration . But this is not possible due to the protected destructor.

I understand that you can use Poco::AutoPtr , but then the resource is lost, making dynamic allocation with new , when automatic allocation should work fine.

My question is: what is the reason for this and I don’t notice anything?

+5
source share
2 answers

As already mentioned, Poco :: RefCountedObject protected the destructor, so all classes inherited from it cannot be created on the stack. The reason is that they are deleted when the number of links reaches zero, so creating them on the stack will lead to undefined behavior - they are mainly intended for use with Poco :: AutoPtr, but this is not necessary - you can also reference the counter manually using duplicate () and release ().

By looking at your code, you are probably looking for a WinRegistryKey , which you can use as follows:

 std::string get_documents_folder() { Poco::Util::WinRegistryKey regKey("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"); return regKey.getString("Personal", ""); } 
0
source

The reason is that WinRegistryConfiguration is calculated by reference (inherited from Poco :: RefCountedObject). A protected destructor is designed to prevent clients from instantiating a class on the stack or directly deleting an object. Instead, you should instantiate the class via new and manage the lifetime using the RefCountedObject methods.

I am not familiar with Poco, but there should also be a smart pointer class that manages reference counting objects by automatically calling RefCountedObject methods.

+1
source

All Articles