Singleton done right in C++ 11

Today searching the internet I’ve found a “cool” and simple method to create a safe singleton that performs well in multithreading environment.

With a small amount of lines you can achieve both: safe initialization and multithreading safety.

class Singleton {
     static std::once_flag onceFlag;
     static Singleton* instance;
public:
     static Singleton& getInstance(){
          std::call_once(onceFlag, []{
               instance = new Singleton();
          });
          return *instance;
     }

private:
     Singleton(){};
}

 

As c++ documentation says the:

  • The class std::once_flag is a helper structure for std::call_once.
    An object of type std::once_flag that is passed to multiple calls to std::call_once allows those calls to coordinate with each other such that only one of the calls will actually run to completion.
    std::once_flag is neither copyable nor movable.
  • The std::call_once executes the Callable object f exactly once, even if called from several threads.

 

Having this in mind stay save and use singleton in a safe way!

Happy coding!

Programator, împătimit al tehnologiei. Absolvent al Universității Politehnica din Timișoara, in prezent dezvoltator de soluții software C++/Web

Leave a reply:

Your email address will not be published.