Thread Safe singleton in C++ using static member instance (no lazy instantiation)

I am aware of the Meyers singleton:

class Singleton{
private:
    Singleton();

public:
    Singleton & GetInstance(){
        static Singleton instance;
        return instance;
    }
}

The advantages of it is that it uses lazy evaluation but it is not guaranteed to be thread-safe in C++ 03.

What if the static instance is a member variable? Is that guaranteed to be thread-safe? I don't see why not. Moreover I'm willing to give up the lazy instantiation for that.

class Singleton{
private:
    Singleton();
    static Singleton instance;

public:
    Singleton & GetInstance(){
        return instance;
    }
}

Answers


If you change the singleton instance to be a static class member, the creation of that instance will be thread safe. Whatever you do with it, will of cause still need to be protected in many cases.

Also see When are static C++ class members initialized?


That just defeats the singleton altogether. Yes, it becomes thread-safe. But now it is the same as simply global variable of type Singleton, so why go for that extra typing of Instance() and friends?


While you gain thread-safety, you do not defeat the "static initialization order fiasco" any more, which is in my oppinion the most important aspect of this type of Singleton class.


Need Your Help

Floodfill with "layers"

c++ algorithm flood-fill bounds

What I want is to create a vector drawing program with layers, but to avoid using transparency / opacity, I want to draw each shape from lowest layer to highest layer onto a single bitmap. For the

SSL on Google App Engine trusted for Certificate

google-app-engine ssl certificate

I have created a self signed certificate and of course my website works with https but not trusted.