efficient thread-safe singleton in C++

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

    Does TLS work here? https://en.wikipedia.org/wiki/Thread-local_storage#C_and_C++

    For example,

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

    But we also need a way to delete it explicitly, like

    static void deleteInst() {
       if (!inst) {
         return;
       }
       delete inst;
       inst = NULL;
    }
    

提交回复
热议问题