How do you lazily construct a singleton object thread-safely? [duplicate]

Here’s Meyer’s singleton, a very simple lazily constructed singleton getter:

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

This is lazy, and C++11 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.

See also N2513: Dynamic Initialization and Destruction with Concurrency on this topic.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)