efficient thread-safe singleton in C++

前端 未结 9 1616
醉话见心
醉话见心 2020-11-28 18:30

The usual pattern for a singleton class is something like

static Foo &getInst()
{
  static Foo *inst = NULL;
  if(inst == NULL)
    inst = new Foo(...);
         


        
9条回答
  •  悲哀的现实
    2020-11-28 18:49

    Herb Sutter talks about the double-checked locking in CppCon 2014.

    Below is the code I implemented in C++11 based on that:

    class Foo {
    public:
        static Foo* Instance();
    private:
        Foo() {}
        static atomic pinstance;
        static mutex m_;
    };
    
    atomic Foo::pinstance { nullptr };
    std::mutex Foo::m_;
    
    Foo* Foo::Instance() {
      if(pinstance == nullptr) {
        lock_guard lock(m_);
        if(pinstance == nullptr) {
            pinstance = new Foo();
        }
      }
      return pinstance;
    }
    

    you can also check complete program here: http://ideone.com/olvK13

提交回复
热议问题