Question

Today I saw this pattern for using Singleton and it confused me a lot.

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

Singleton& Singleton::getInstance(){
    static Singeton instance;
    return instance;
}
int main(){
    Singleton &inst = Singleton::getInstance();
    Singleton &inst2 = Singleton::getInstance();
    std::cout << &inst << " " << &inst2;
}

The output of the pointers is the same. Here is an example. I am really confused about it. I would expect every call to getInstance() to create a new (although static) instance of singleton. Could you please explain me the behaviour.

Was it helpful?

Solution

For a reason you posted the source of your function here different than on the page you gave link to:

static Singleton& getInstance(){
  static Singleton instance;
  return instance;
}

Why does it work? The static local object instance in the function is created only once, the first time the function is called - that's because it's static. The next times you call the function it returns reference to the same object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top