1
#include <iostream> using namespace std; class Singleton { public: static Singleton *getInstance(); private: Singleton(){} static Singleton* instance; }; Singleton* Singleton::instance = 0; Singleton* Singleton::getInstance() { if(!instance) { instance = new Singleton(); cout << "getInstance(): First instance\n"; return instance; } else { cout << "getInstance(): previous instance\n"; return instance; } } int main() { Singleton *s1 = Singleton::getInstance(); Singleton *s2 = Singleton::getInstance(); return 0; } 

i didn't understand why should singleton instance variable should be initilized with 0 in the following line. Singleton* Singleton::instance = 0; Because when i forgot to initilize the instance i got error as

singleton.cpp:(.text+0xc): undefined reference to `Singleton::instance' singleton.cpp:(.text+0x2d): undefined reference to `Singleton::instance' singleton.cpp:(.text+0x43): undefined reference to `Singleton::instance' singleton.cpp:(.text+0x5b): undefined reference to `Singleton::instance' collect2: error: ld returned 1 exit status 
1
  • Because it's the rules of C++. static Singleton* instance; is a declaration, but variables have to be defined as well, Singleton* Singleton::instance = 0; is a definition. Commented Jan 21, 2019 at 7:47

2 Answers 2

1

Besides the procedure to initialize a static member in C++, the only reason to initialize a singleton to null is because you explicitly need to initialize at a later stage in your application for some reason (like waiting for other resources to be allocated and/or initialized). Otherwise, it can be initialized during the static declaration. Furthermore, you dont need to deal with pointers to create a Singleton.

class Singleton { public: static Singleton & getInstance(); private: Singleton(){} static Singleton instance; }; Singleton Singleton::instance; Singleton & Singleton::getInstance() { return instance; } 

EDIT: Nevermind, I see your question was oriented towards the static initialization procedure rather than the pattern itself

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

Comments

1

static Singleton* instance; is a declaration and not a definition.

As per [class.static.data]/2

The declaration of a non-inline static data member in its class definition is not a definition...

So without the below line of code,

Singleton* Singleton::instance = 0;` 

instance is not defined in the code. And trying to use it in getInstance will result in undefined reference errors.

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.