Thread-safe singleton in C++11

后端 未结 2 753
Happy的楠姐
Happy的楠姐 2021-01-20 18:59

I know the following is a thread-safe way to implement a singleton in C++11:

Foo* getInst()
{
    static Foo* inst = new Foo(...);
    return inst;
}
         


        
2条回答
  •  無奈伤痛
    2021-01-20 19:50

    inst in your example won't be allocated on stack. It will be allocated somewhere in .data or .bss section. Otherwise this static variable couldn't live all the time program executes, and so it couldn't have the same value, which was before, each time you enter this function.

提交回复
热议问题