Double-Checked Lock Singleton in C++11

I think this a great question and John Calsbeek has the correct answer.

However, just to be clear a lazy singleton is best implemented using the classic Meyers singleton. It has garanteed correct semantics in C++11.

ยง 6.7.4

… If control enters
the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for
completion of the initialization. …

The Meyer’s singleton is preferred in that the compiler can aggressively optimize the concurrent code. The compiler would be more restricted if it had to preserve the semantics of a std::mutex. Furthermore, the Meyer’s singleton is 2 lines and virtually impossible to get wrong.

Here is a classic example of a Meyer’s singleton. Simple, elegant, and broken in c++03. But simple, elegant, and powerful in c++11.

class Foo
{
public:
   static Foo& instance( void )
   {
      static Foo s_instance;
      return s_instance;
   }
};

Leave a Comment