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!

no responses for Singleton done right in C++ 11

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.