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.
Related
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.
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;
}
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.
Im working on a programming assignment involving the use of static variables/methods. This is one of the requirements, and I'm not exactly sure the proper syntax for declaring it in the header and defining it in the class file:
"Declare a static method of the class with a return type of a reference to an object of the class; name this method “instance”."
heres my guess for declaring:
static &Singleton instance();
heres my guess for defining:
static &Singleton::Singleton instance(){
static myObj;
return myObj;
}
I don't think thats correct.. Could anyone confirm/correct me? Thanks!
You got it almost right.
Declaration:
static Singleton& instance();
Definition:
Singleton& Singleton::instance() {
static Singleton myObj;
return myObj;
}
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().