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
  • 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. – john Jan 21 '19 at 07:47

2 Answers2

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.

Holt
  • 36,600
  • 7
  • 92
  • 139
P.W
  • 26,289
  • 6
  • 39
  • 76
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

Nadir
  • 1,799
  • 12
  • 20