Search code examples
c++c++11design-patternssingletonstd

create singleTon class using std::call_once


The following code is an implementation of an alternative singleTon class that uses std::call_once in C++11. Basically, the variable static_instance is declared statically along with static_flag, and once calling getInstance function which is also static function i create the first and only instance of mySingle using call_once.

I'd be happy to hear for any comments regarding code correctness in terms of thread safety, and whether its behavior differ from the standard c++ implementation of defining static variable inside getinstance.

mySingle.h

class mySingle
{
    static mySingle *static_instance;
    static std::once_flag static_flag;
public:

    mySingle();
    virtual ~mySingle();
    static mySingle* getInstance();
};

mySingle.cpp

#include "mySingle.h"

mySingle * mySingle::static_instance;
std::once_flag mySingle::static_flag;

mySingle::mySingle(){}
mySingle::~mySingle(){}

mySingle* mySingle::getInstance()
{
    std::call_once(g_flag, [&]() { static_instance = new mySingle(); });
    return (mySingle*) static_instance;
}

Solution

  • From the std c++ call_once, it says

    Executes the Callable object f exactly once, even if called concurrently, from several threads.

    So one would expect that this is thread safe