Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top