Reputation: 157
Please tell me why the singleton code below works? Every time When Singleton::instance()
is called, an INSTANCE will be created, so are two INSTANCE supposed to be created in the following code?
#include <bits/stdc++.h>
using namespace std;
class Singleton
{
private:
Singleton() = default;
public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
};
int main()
{
Singleton &s1 = Singleton::instance();
Singleton &s2 = Singleton::instance();
return 0;
}
Upvotes: 0
Views: 92
Reputation: 48288
you can go line by line:
1.
Singleton &s1 = Singleton::instance();
you call here the static method instance()
, inside that method you see the line
static Singleton INSTANCE;
the trick here is to understand that variables declared static inside a method will only declared once, no matter how many times you call the method after. So it creates the instance of Singleton
and it gets returned
2.
Singleton &s2 = Singleton::instance();
the second call will actually skip the delaration of INSTANCE and will return that immediatly.
for more clarifying you can put some meaningful messages in the constructor
something like
std::cout << "Contructor called!" << std::endl;
even better if you use a static variable as a counter just for testing purposes.
Upvotes: 2
Reputation: 238401
Every time When Singleton::instance() is called, an INSTANCE will be created, so are two INSTANCE supposed to be created in the following code?
No. Only one instance is created.
each time when expression static Singleton INSTANCE; executed. Isn't different INSTANCE created?
No.
I know what static means
Evidently, you don't know what you think you know.
Upvotes: 0
Reputation: 122830
You should read about the static
keyword. It can have different meaning and here you have two of them:
static Singleton& instance()
// ^ ---------------------------- (1)
{
static Singleton INSTANCE;
// ^ ------------------------- (2)
return INSTANCE;
}
The first static
declares the method instance
as a "class-method" (or simply "static method"). You can call the method without having an instance.
The second static
declares that INSTANCE
has static storage duration. That is: There is only one. It is initialized once and when you reenter the function you get the exact same instance.
Upvotes: 3