GPPK
GPPK

Reputation: 6666

Do I need static variables in a singleton class?

Take the below code. If I were to add some private member data into this class, say a std::vector, would I make it static or not?

#include <string>

class Logger{
public:
   static Logger* Instance();
   bool openLogFile(std::string logFile);
   void writeToLogFile();
   bool closeLogFile();

private:
   Logger(){};  // Private so that it can  not be called
   Logger(Logger const&){};             // copy constructor is private
   Logger& operator=(Logger const&){};  // assignment operator is private
   static Logger* m_pInstance;
};

**Code example shamelessly taken from here

Upvotes: 0

Views: 70

Answers (2)

James Kanze
James Kanze

Reputation: 153899

The big problem is order of initialization. In C++, the singleton idiom is usually used to resolve order of initialization issues, so that's likely to be a problem: if the members are static, you can't be sure that they have been constructed before you try to use them.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

Idiomatically, no. Other than that, there's nothing that keeps you from doing it.

Keep in mind though that if it is static, it needs to be defined and the member gets initialized before entry to main, when the program starts.

If it isn't static, it will get initialized when m_pInstance gets created (which can be useful if you need some lazy initialization).

Upvotes: 3

Related Questions