efficient thread-safe singleton in C++

前端 未结 9 1613
醉话见心
醉话见心 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:50

    If you are using C++11, here is a right way to do this:

    Foo& getInst()
    {
        static Foo inst(...);
        return inst;
    }
    

    According to new standard there is no need to care about this problem any more. Object initialization will be made only by one thread, other threads will wait till it complete. Or you can use std::call_once. (more info here)

提交回复
热议问题