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; } } 
1

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.