Thread safe lazy construction of a singleton in C++

后端 未结 9 1580
梦毁少年i
梦毁少年i 2020-11-29 19:22

Is there a way to implement a singleton object in C++ that is:

  1. Lazily constructed in a thread safe manner (two threads might simultaneously be the first user o
9条回答
  •  佛祖请我去吃肉
    2020-11-29 19:54

    You can't do it without any static variables, however if you are willing to tolerate one, you can use Boost.Thread for this purpose. Read the "one-time initialisation" section for more info.

    Then in your singleton accessor function, use boost::call_once to construct the object, and return it.

提交回复
热议问题