Tutoriale

Singleton done right in C++ 11

By on 11/07/2017

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!

TAGS
RELATED POSTS
VLAD VESA
Timisoara, RO

Hi my name is Vlad and this is my Journey! I use this awesome blog theme to tell people my story. Through all the places and things I see around the world, there isn't a better way to share my experience! Follow my daily updates and discover with me the essence of traveling!

Latest tweets
  • Trying out @theTunnelBear so I can browse privately from my ISP https://t.co/nTKZxipi9d https://t.co/nGJHmMue9O

    Tweeted on 10:41 PM Oct 27

  • just bought a @lenovo yoga 720 beautiful machine! good build quality and unexpected package content! https://t.co/nNHj7WCK6A

    Tweeted on 10:13 PM Oct 27