I could not able to understand how Singleton works? - c++

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

Related

How to understand Singleton in 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.

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!

C++ how to delete Singleton object's used in many classes

Let's say I have 3 classes(A, B and C). Every class has an instance variable of the Singleton class and uses this instance variable in some functions of the class.
This class could look like this:
SingletonClass* mSingletonClass; // declared in header file
mSingletonClass = SingletonClass::getInstance(); // called in constructor
mSingletonClass->doSomething(); // called in function doSomething()
mSingletonClass->doSomething1(); // called in function doSomething1()
SingletonClass.h
class SingletonClass : public QObject {
Q_OBJECT
public:
static SingletonClass* getInstance();
// some functions
private:
SingletonClass();
SingletonClass(SingletonClass const&);
SingletonClass& operator=(SingletonClass const&);
static SingletonClass* mInstance;
};
SingletonClass.m
SingletonClass* SingletonClass::mInstance = 0;
SingletonClass* SingletonClass::getInstance() {
if (!mInstance) {
mInstance = new SingletonClass();
}
return mInstance;
}
SingletonClass::SingletonClass() : QObject() {
}
How am I supposed to delete the instance variables?
If I call delete mSingletonClass; on every deconstructor(A, B and C), the application crashes.
Is it "enough" if I just call delete mSingletonClass; once, for instance in Class A?
You never destroy singleton object in any of the classes that use it. The very reason the singleton is a singleton is that there is only one instance of it in your system, created once, and kept forever, until your program is about to exit.
John Vlissides discusses one way to destroy singletons in his C++ Report article called To Kill A Singleton. He suggests using a special "guard" object that deletes a pointer to singleton upon destruction. In modern C++ you can achieve the same effect by pointing a unique_ptr<T> to the instance of your singleton (you can use it for your mInstance variable).
You can put a static member variable (e.g. SingletonClassDestroyer) inside the SingletonClass to help destroy it since the lifetime of a static member variable ends when program terminates. SingletonClassDestroyer should take the SingletonClass instance and destroy it in its own destructor ~SingletonClassDestroyer(). Thus, SingletonClassDestroyer will help you automatically destroy SingletonClass instance in the end.

Method calling a the static singleton instance to call another method

I'm browsing some random code and I found some confusing method, the class is a singleton,
class CFoo
{
CFoo* _instance;
CFoo(){};
public:
~CFoo(){};
static CFoo* getInstance()
{
if(!_instance)
_instance = new CFoo;
return _instance;
}
static void deleteInstance()
{
if(_instance)
delete _instance;
}
// just ordinary member method.
void FooMethod()
{
CFoo::getInstance()->BarMethod(); //confusing..
}
// just ordinary member method.
void BarMethod()
{
//code here..
}
};
CFoo* CFoo::_instance = NULL;
Why FooMethod have to call the CFoo::getInstance() to call the BarMethod? Why not just calling BarMethod() directly?
Please advise.
If you call CFoo::getInstance()->BarMethod() within CFoo::FooMethod(), then the this keyword in the BarMethod refers to CFoo::_instance.
If you call BarMethod() within CFoo::FooMethod(), then the this keyword in the BarMethod refers to the same object on which FooMethod() was called.
It is not entirely clear whether there is effectively any difference. On the one hand, the only constructor that you implemented is private and you refer to the class as a Singleton. This supports the fact that only one instance of CFoo should exist, i.e. this == CFoo::_instance should always hold within BarMethod. On the other hand, CFoo has a public copy constructor, so this == CFoo::_instance might not always be true within BarMethod.
You could call the FooMethod and the Barmethod directly if you could create an object of this class. the problem is you can't do it because the construtor is private. the only way you can create the instance is using the getInstance method. and the method ensure it had no more than single object of this class.
That's why it called singleton.

What exactly does getinstance() do in a singleton?

I have come across the singleton pattern.
I was unable to understand the difference between
singletonobj.getinstance().dosomething() //1st one
and
singletonobj.dosomething() //2nd one
What does getinstance() do, that isn’t being done in the second case?
Well, technically, singletonobj.getinstance() is redundant, because that means you already got a hold of the object.
The call would usually look something like:
SingletonClass::getinstance().dosomething();
or
singletonobj.dosomething()
in case you pre-fetched the object - i.e. previously did
SingletonClass& singletonobj = SingletonClass::getinstance();
First, singletonobj is a wrong/confusing name. Singletons are called on a class basis, like:
Log::getInstance().doSomething();
and not
Log log = new Log;
log.getInstance().doSomething();
So this should answer the question, but I'll detail anyway :)
Log::doSomething();
would force doSomething() to be a static method, while
Log::getInstance().doSomething();
has doSomething() as an instance method.
Why use getInstance()? Because a singleton, by its very definition, should only have zero or one instances. By making the constructor for a singleton private and publishing the getInstance() method, it allows you to control how many instances of this class there are. The private constructor is simply to avoid other classes to instance this class, which would defeat the purpose of this class being a singleton, as you wouldn't be able to control how many instances of this class there are.
class SingletonExample {
private:
static SingletonExample* instance = NULL;
SingletonExample() { }
public:
static SingletonExample getInstance() {
if (instance == NULL) {
instance = new SingletonExample;
}
return *instance;
}
void doSomething() {
// Do something :)
}
}
It would appear that that the first example is calling a regular method, whereas the second example is calling a static method.
The Singleton design pattern ensures that only a single instance of a given object is instantiated at any given time. The first example returns said instance, and then calls a method using an instance of an object.
The second example appears to be using a static method that does not require an instance of an object and actually invalidates the singleton design pattern...