How to understand Singleton in c++? - c++

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;
}

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.

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.

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.

Related

c++ / difference between this and static class name

One question according this code
Cl& Cl::getInstance()
{
static Cl instance;
return instance;
}
What do I achieve through this code and which difference would be if I would return this.
*this method is static
If the method is static, this is not implicitly defined, so the question doesn't apply.
On the other hand, if the method is a non-static member there's a huge difference.
Cl& Cl::getInstance()
{
static Cl instance;
return instance;
}
here you always return the same instance even called from several instances of the same class: a singleton (Misleading as the returned instance has nothing to do with the caller instance)
Cl& Cl::getInstance()
{
return *this;
}
above, you're returning the current instance (not of great interest...)
EDIT: maybe your question is related to the singleton design pattern where no object can obtain a valid Cl object without using getInstance() because the constructor is private, and in that case, the interest is that it returns the same instance for every caller:
Cl& Cl::getInstance() // static method
{
static Cl instance; // constructor is private, only can be called from here
return instance;
}

what is the exact use and implementation of singleton class?

I know the singleton class does not allow to create more than one object. but as per my below code i can create as many objects as possible.
class Singleton
{
private :
static Singleton *m_Instance;
Singleton()
{
cout<<"In defailt constructor"<<endl;
}
Singleton(int x)
{
i = x;
cout<<"in param const"<<endl;
}
public:
static int i;
static Singleton* createInstance()
{
if(!m_Instance)
m_Instance = new Singleton(20);
Singleton sing;
return m_Instance;
}
};
int Singleton::i=0;
Singleton* Singleton::m_Instance = NULL;
int main()
{
Singleton *pt = Singleton::createInstance();
return 1;
}
Here I am able to create an object in the static function (as i can access constructor within the class) then where is the concept of Single object?
This isn't a singleton for the simple reason that you deliberately wrote something that isn't a singleton.
The idea is that you write the instance function so that it will only create one instance, and write other members so that they don't create any. Then, since they're the only functions that could create any instances, there will only be one.
If you remove the dodgy Singleton sing;, then you'll have a singleton implementation - only one instance will be created, the first time someone calls the function.
As with all attempts to implement this anti-pattern in C++, there are problems: the object is never destroyed, and the initialisation isn't thread-safe. There are various other approaches, each with their own drawbacks. I suggest you avoid global variables altogether, whether or not you dress them up as singletons or other anti-patterns.
The concept of single object comes when in your code, every time you need an instance of your Object, instead of using:
Singleton *myOwnSingleton= new Singleton(20);
You should always use:
Singleton *pt = Singleton::createInstance();
As the constructor is inaccesible outside of the class, the only way to create a Singleton is by Singleton::createInstance(), and if you read the code, only the first time that we call Singleton::createInstance() a new instance is created.
All subsequent calls to this method will return the already created object. So in all your execution you will only have one instance created.
But of course... you should delete the line
Singleton sing;
because it is a wrong utilization of Singleton. If you create a class called CAR but without wheels... it is not a car. And you make a class called singleton, but... with two objects of the same type. It's not beauty!

Static variable initialization as a class member or local function variable (Singleton example)

I will demonstrate my question using a Singleton pattern but it is a broader question. Please spare me the "Singletons are evil" lectures.
Version 1 of Singleton
class Singleton
{
public:
static Singleton& getInstance()
{
static Singleton instance; // This becomes a class member in Ver.2
return instance;
}
private:
// Constructor, forbid copy and assign operations etc...
}
Version 2 of Singleton
class Singleton
{
public:
static Singleton& getInstance()
{
return instance;
}
private:
static Singleton instance; // I'm here now!
// Constructor, forbid copy and assign operations etc...
}
I will now explain what I think will be the difference is between the two:
Version 1 instance will only be initialized once the flow of the program reaches the actual definition of instance (i.e some part of the program requests an instance using Singleton::getInstace()). Lazy instantiated in other words.
It will only be destroyed when the program terminates.
Version 2 instance will be initialized at the start of the program, before main() is called. Will also be destroyed only when the program terminates.
First of all, am I correct in the above assumptions?
Second, Is this behavior of initialization universal (say for global variables and functions)?
Last, Are there any other nuances I should be alerted about concerning this?
Thanks!
You are correct.
You should also notice that the 2nd version does not guarantee when will the object be created, only that it will be before the main function is called.
This will cause problems if that singleton depends on other singletons and etc
That is, the first version will give you greater control over your code, initialization order and of course - less bugs :)

Why this singleton implementation works?

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.
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.

I could not able to understand how Singleton works?

I am good at C++, but trying to understnd how singleton works. So I was looking into the code or article HERE .
If I will see the code;
class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{/*private constructor*/}
public:
static Singleton* getInstance();
void method();
~Singleton()
{instanceFlag = false;}
};
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{return single;}
}
void Singleton::method()
{cout << "Method of the singleton class" << endl;}
int main()
{
Singleton *sc1,*sc2;
sc1 = Singleton::getInstance();
sc1->method();
sc2 = Singleton::getInstance();
sc2->method();
return 0;
}
In this above code that prints Method of the singleton class twice.
If we wanted to print the output twice, then why do we need singleton.
We can write like;
sc1->method();
sc2->method();
Why do need such a complicated code as written above.
One thing I noticed, instanceFlag is becoming true once condition satisfies with onject sc1 but when the object sc2 gets called then it goes to else part.
So, what exactly we are trying to do here?
You might want to read up wikipedia to understand what Singleton means
Essentially, for situations where you want to have only 1 object of a class at any time, you use such a pattern
In this code, Singleton::getInstance() is meant to return this 1 object of the class. The first time you call it, the object is constructed. Subsequent calls to Singleton::getInstance() will be returned the same object. instanceFlag tracks if the object has been instantiated.
Another hint is that the constructor is private, this means there is NO way to get an instance of the class except by the GetInstance() function.
p.s. I do agree with you though, this code is more convoluted than im used to.. It also (technically) has a memory leak .. the instance is never deleted
This is what i see more often
static Singleton* getInstance()
{
static Singleton instance;
return &instance;
}
As the name suggests Singleton design patter is used when we need at max one object of a class.
Below is a simple explanation of how singleton is achieved.
Sometimes we need to declare a class which allows creation of only one instance of it .
Suppose you are creating a media player of your own and you want it to behave like windows media player,which as we all know, allows only one instance to be created and it would would not be possible to run two windows media players simultaneously. Technically speaking we can create only one object of windows media player.
To implement this concept we can declare our class in the following way:
class media_player // Class for creating media player
{
static media_player player = null; // static object of media_player which will be unique for all objects
other static members........... // you can provide other static members according to your requirement
private media_player() // Default constructor is private
{
}
public static createInstance( ) // This method returns the static object which will be assigned to the new object
{
if(player==null) // If no object is present then the first object is created
{
player = new media_player();
}
return player;
}
other static functions.............. // You can define other static functions according to your requirement
}
If we create any object of this class then the staic object (player) will be returned and assigned to the new object.
Finally only one object will be there.
This concept is also used to have only one instance of mouse in our system.i.e. we can not have two mouse pointers in our system.
This type of class is known as singleton class.
The point is not how many times something gets executed, the point is, that the work is done by a single instance of the the class. This is ensured by the class method Singleton::getInstance().