I was reading the C++11 FAQ and noticed this:
class X4 { ~X4() = delete; // Disallow destruction }
This implicitly also disallows moving of X4s. Copying is allowed, but deprecated.
I also found this quote.
Deleting the definition of a destructor will require allocation on the free-store because static and automatic objects implicitly invoke the destructor:`
struct C { ~C()= delete; //prevent automatic and static objects };
However, this technique is less useful than it may seem because it prevents delete expressions, too. Singleton objects can use it, though.`
Which makes sense. My question is, is it considered good practice have a Singleton with an explicitly deleted destructor? Also, if anyone knows of any other case scenarios were you shouldn't call delete
, please let me know.
Pragmatically, you might sometimes find yourself in a situation where it's unsafe to destroy objects of a particular type. So you'd delete the destructor to prevent anyone trying.
In the case of a Singleton, where there's only ever going to be one instance of the type, failing to destroy it might be less harmful than if there are loads of instances not cleaned up.
One of the problems with Singletons (or any other globally-available object) is that you can lose control of the dependencies on them. Then it's hard to work out a safe order of destruction -- if the global database object logs to the global logger object that you've closed the connection safely, but optionally the global logger object does its logging to the database via the global database object, then you have a problem.
Although you might "solve" this problem by not destroying the global database object, I don't think this should really be called "good practice". It sounds more like a simple way to deal with a bad situation without re-design (although in my example the redesign might be pretty simple too - just make sure that either the DB logger, or the DB itself, does something useful with log messages when the connection is closed. Swallow them, or redirect them to another available destination).
It may be that there are "good" designs in which a particular type of object cannot be destroyed, but it's not the usual way C++ classes are designed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With