I’d use a singleton like this:
Singleton* single = Singleton::instance(); single->do_it();
I’d use an unnamed class like this:
single.do_it();
I feel as if the Singleton pattern has no advantage over the unnamed class other than having readable error messages. Using singletons is clumsier than using an unnamed class object: First, clients must first get a handle of the instance; second, the implementer of Singleton::instance() might need to consider concurrency.
So why and how would you choose a singleton over an unnamed class?
As an addendum, although the obvious definition of an unnamed class might be
class { // ... }single;
I could as well define it like so:
#ifndef NDEBUG class Singleton__ { // readable error messages, #else class { // unnamed, clients can't instantiate #endif // ... }single;
with the latter approach having the advantage of readable compiler error messages but not being a singleton in debug mode.
I think the most important reason is that you cannot put an unnamed class in namespace scope. So, the following is not valid (gcc accepts, but warns. comeau doesn’t accept in strict mode):
The type of
singlehas no linkage because there is no way to declare its name in another scope referring to it (precisely because it has no name). But using it to declaresingle, which has linkage (external here) is not valid (3.5/8).singlehas to be defined locally in main where it will have no linkage. You also cannot pass single to function templates and it can’t have static data members (because there is no way to define them). All those restrictions make it more or less not applicable as a substitution for a singleton.