views:

1055

answers:

2

I'll soon be posting an article on my blog, but I'd like to verify I haven't missed anything first.

Find an example I've missed, and I'll cite you on my post...

The topic is failed Singleton implementations - in what cases can you accidentally get multiple instances of a singleton?

So far, I've come up with

Race Condition on first call to instance() Incorporation into multiple DLLs or DLL and executable Template definition of a singleton - actually separate classes

Any other ways I'm missing - perhaps with inheritance?

Please help improve my post...

+1  A: 

Inheritance shouldn't be an issue as long as the ctor is private.

However, if you don't disallow the copy constructor, users may [un]intentionally copy the singleton instance. Privately inheriting from boost::noncopyable is the easiest way to prevent this.

David Joyner
Instead of using inheritance, it is much better to just declare the two troublesome methods as private. Saves an inclusion of boost if you don't want to bring it in, and using inheritance (both minor costs, but good to know)
hazzen
That's a valid option too and what I used to do. Why don't you post that as an alternative answer? BTW, better is subjective... the boost::noncopyable method yields a compiler error with a specific line number. Your method yields a link-time error which can be harder for newbies to track down.
David Joyner
+2  A: 

If you use a static instance field that you initialize in your cpp file, you can get multiple instances (and even worse behavior) if the initialization of some static/global tries to get an instance of your singleton. This is because the order of static initialization across compilation units is undefined.

On Freund
So what you are saying is the global memory used by _instance is initialized to NULL, one other global variable calls instance() allocating instance #1, then the explicit _instance initializer executes, setting it back to NULL, and the next call to instance() allocates a second time?
theschmitzer
So the question then is what does global memory look like prior to initialization of global data members...
theschmitzer
The point is that global memory is initialized to NULL before main, but not necessarily before you've requested a singleton instance.
On Freund