0

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;
    }
}
Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
  • maybe have a look at this answer also: http://stackoverflow.com/questions/34744811/global-variables-in-modern-c – Chris Beck Jan 14 '16 at 17:23

3 Answers3

2

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?

Community
  • 1
  • 1
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
1

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?

SergeyA
  • 61,605
  • 5
  • 78
  • 137
1

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.

Michael Karcher
  • 3,803
  • 1
  • 14
  • 25