A Simple and Clean Singleton in C++

I've seen lots and lots of examples of bad singleton implemenations in C++, including this one on the Dutch Wikipedia.

There's a number of things the Wikipedia implementation does badly (or could at least have been done better)

  • getInstance() returns a pointer. There's no reason whatsoever for this.
  • The assignment m_pSingleton = new CSingleton; can be forgotten without a compile-time warning, resulting in a runtime segfault
  • The conditional if(m_pSingleton == NULL) (which should have been written as if(!m_pSingleton) or if(m_pSingleton == 0) anyway, read "The C++ Programming Language" by Stroustrup and realise that C and C++ are two different languages) can be forgotten resulting in confusing behavior

A much better solution looks like this:


class SomeClass
  SomeClass(){ /* Do whatever */ };

  static SomeClass& get()
   static SomeClass instance;
   return instance;

  void doStuff()
  { std::cout << "stuff\n"; } 

int main()
 return 0;

Let's see if my earlier comments on the Wikpedia example still apply:

  • get() (the getInstance() equivalent, feel free to name this function getInstance()) returns a reference, not a pointer.
  • If the initialisation (static SomeClass instance;) is forgotten, this will result in a compile-time error
  • There is no check, the code that makes sure the instance is only instantiated once is generated automatically by the C++ compiler
Also, by choosing my implementation over the Wikipedia one, the amount of code needed to return an instance is halved from 4 lines of code in the Wikipedia example (excluding all lines of code that are equivalent) to 2 lines of code in my example.

No comments:

Post a Comment