title: C++ singleton pattern using boost::call_once
body: <p>Singletons in C++ (at least prior C++11 AFAIK) can be a nightmare. With the whole static initialisation order fiasco. But boost::call_once seems to offer a robust way to implement singletons. I've tried to come up with an easy to use idiom I'd like to share for some critical feedback, hope I haven't been completely foolish :)</p>
  
  <pre><code>// Usage:
  // You can make anything with a public or protected ctor a singleton.
  //
  // class A
  // {
  // public:
  //     ~A();
  // public:
  //     // Optional, shorter to type
  //     static A&amp; Instance() { return Singleton&lt;A&gt;::Instance(); }
  //     void foo();
  //
  // protected:
  //     explicit A(); // Can't be private, but can be public, protected is recommended.
  // };
  //
  // Singleton&lt;A&gt;::Instance().foo();
  // A::Instance().foo();
  //
  template&lt; class T &gt;
  class Singleton : public T // inerits from T so we can access the protected constructor.
  {
  public:
      virtual ~Singleton() {}
  
  public:
      static T&amp; Instance();
  
  private:
      static boost::once_flag s_onceFlag;
      // We use a raw pointer to avoid dynamic initialisation. If something that
      // has a constructor (eg, shared_ptr ) then the dynamically initialised ctor
      // may get called after the call once function is called (if the call once function
      // is statically invoked before main). Then the instance pointer will be overwritten.
      // Using a zero initialised pointer avoids this problem.
      static T* s_instance;
  
  private:
      static void Init();
  
  private:
      explicit Singleton() {} // Used only to allow access to the protected ctor in base.
  };
  
  
  
  template&lt; class T &gt;
  boost::once_flag Singleton&lt;T&gt;::s_onceFlag = BOOST_ONCE_INIT; // zero initialised variable, no order o initialisation shananigans
  
  template&lt; class T &gt;
  T* Singleton&lt;T&gt;::s_instance = 0;
  
  template&lt; class T &gt;
  void Singleton&lt;T&gt;::Init()
  {
      static Singleton&lt;T&gt; instance; // static local variable is thread safe since this function is called once only.
      s_instance = &amp;instance;
  }
  
  
  template&lt; class T &gt;
  T&amp; Singleton&lt;T&gt;::Instance()
  {
      boost::call_once( s_onceFlag, Init );
  
      return *s_instance;
  }
  </code></pre>