Whether you call it Singleton or Monostate or any fancy name... the very annoying nature of this is that you have ONE instance of the object and many writes to it: global variables, whatever their guise, are evil.
The idea that you need a unique instance is generally clunky. Most of the times what you really need is parts that communicate share the same instance. But another group of parts could perfectly use another instance without issue.
Any code that claim to need a global variable is highly suspicious. It may appear simpler to use one, but let's face it, you could perfectly pass the object to each and every function, it would complicate their signature but it would work nonetheless.
However, I admit, it appears simpler to use global variables... until you notice the issues:
- multithreading is compromised
- testability is reduced, since one test may affect the one following it
- dependency analysis is extremely complicated: it's hard to know what state your method depend on when you pull in global from within submethods...
Now, as far as singleton is concerned, multithreaded creation is not usable in C++ before C++0x (when it becomes possible using static locals), thus you need to create it in only one thread and delay access before: instantiate it in main, it's your best bet.
Destruction may cause mayhem since the life of the Singleton / Static may end before others are done with it, and then it's undefined behavior. This is typical of a Logger
singleton. The usual strategy is to shamelessly leak...
After that, if you still want one, I wish you good luck, that's all this community can do for you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…