Thread safe lazy construction of a singleton in C++

后端 未结 9 1582
梦毁少年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:50

    Here's a very simple lazily constructed singleton getter:

    Singleton *Singleton::self() {
        static Singleton instance;
        return &instance;
    }
    

    This is lazy, and the next C++ standard (C++0x) requires it to be thread safe. In fact, I believe that at least g++ implements this in a thread safe manner. So if that's your target compiler or if you use a compiler which also implements this in a thread safe manner (maybe newer Visual Studio compilers do? I don't know), then this might be all you need.

    Also see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2513.html on this topic.

提交回复
热议问题