J
Joshua Maurice
Yes, misuse of singletons can be a disaster, a maintenance nightmare.
Have you ever been forced to weed through all the uses of such a "kewl
global variable" just to figure out wtf will happen if there are two
of them, because of course now you need two of them?
The idea that a programmer can know that there /must never ever/ be
more than one instance of a class T is, to be perfectly frank, nearly
laughable.
Now, of course, one may know that at this particular time we need
a /common/ shared instance but this is easily achieved with a non-
intrusive smart "pointer" template such as the singleton template
Leigh gave or the very similar (though having more features)
"common" template of mine. For example my
  common<Foo> foo ;
is a kind of smart pointer to a common instance of Foo. These days
I can think of absolutely no, nada, zero reasons why I would want to
pollute a Foo type with intrusive "singleton" scaffolding. If anyone
knows of good reasons for intrusive singletons please enlighten me.
KHD
PS. I think singleton is so heavily abused because 1) the name
sounds kewl 2) it constrains usage of the class and even if that
constraint is useless programmers love to naively force their will
on other programmers 3) it's famous so you can throw it around as
a buzzword and seem smart 4) it also happens to provide a global
variable replacement and one that has been /approved/ by all the
kewl kids 5) you are mocked as a "C" programmer if you are honest
and just use a plain global variable (or free function).
With respect, if you are abstracting some system resource, then it
makes sense to be "global" in the colloquial sense and to use a
singleton. You can't change the fact that you have only one disk (or
disk subsystem), nor can you change the fact that you have only 1 OS
and process / thread scheduler, and so on.
However, I agree that most uses of singleton are not that.