How to implement multithread safe singleton in C++11 without using

C++11 removes the need for manual locking. Concurrent execution shall wait if a static local variable is already being initialized.

ยง6.7 [stmt.dcl] p4

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

As such, simple have a static function like this:

static Singleton& get() {
  static Singleton instance;
  return instance;
}

This will work all-right in C++11 (as long as the compiler properly implements that part of the standard, of course).


Of course, the real correct answer is to not use a singleton, period.

Leave a Comment