c++ / difference between this and static class name - c++

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

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.

Singleton object using unique_ptr

I have the below CPP source code for creating a Singleton Object of a class using unique_ptr:
#include <iostream>
#include <memory>
class A
{
public:
std::unique_ptr<A> getInstance(int log);
~A();
private:
static bool instanceFlag;
static std::unique_ptr<A> single;
A(int log);
int mLog;
};
bool A::instanceFlag = false;
std::unique_ptr<A> A::single = NULL;
std::unique_ptr<A> A::getInstance(int log)
{
if(!instanceFlag)
{
//single = std::make_unique<A>(log);
single = std::unique_ptr<A>(new A(log));
instanceFlag = true;
return std::move(single);
}
else
{
return std::move(single);
}
}
A::A(int log) :
mLog(log)
{
std::cout << "Called A cons" << std::flush << std::endl;
}
int main()
{
std::unique_ptr<A> mA = A::getInstance(5);
}
But when I compile the code I get below error:
$ c++ -std=c++11 try2.cpp
try2.cpp: In function 'int main()':
try2.cpp:45:41: error: cannot call member function 'std::unique_ptr<A> A::getInstance(int)' without object
std::unique_ptr<A> mA = A::getInstance(5);
^
However I have exactly the same format of code in my project I get an error :
Source code Line 39: single = std::make_unique<A>(log);
Compilation error:
39: required from here
single = std::make_unique<A>(log);
error: A(int log)' is private
A::A(int log) :
^
First, the static issue. This:
std::unique_ptr<A> getInstance(int log);
is an instance method. You need an instance of A to call it on, but you can't get an instance of A without calling this method first, so ...
The reason for using instance methods is that they have access to the instance they're invoked on. Your method only uses the following members:
static bool instanceFlag;
static std::unique_ptr<A> single;
which, since they're static, don't need an instance. Just make the method static too, and you'll be able to call it without first getting an A from somewhere.
Second, the logic issue. Your getInstance method returns a unique_ptr to your single instance. The entire point of unique_ptr is that's it's unique: exactly one pointer owns and controls the lifetime of an object. When you returned a unique_ptr, you transferred ownership of the singleton object from the singleton class itself, to the caller. You even explicitly called move to make it really clear that this is happening.
Now, after calling getInstance once, your singleton is completely broken. If you call getInstance again, the singleton believes it has an instance (because instanceFlag), but the unique_ptr is in an indeterminate state. The only thing we can say for sure is that it doesn't control an instance of A.
Just return a raw pointer (or reference) to A instead of transferring ownership.
Short answer: Don't use singletons.
Long answer: std::make_unique() uses constructor of an object it tries to create, and in your code it's private. Since it is an external function, it's not possible. You can create an object on your own and pass it to std::unique_ptr to manage, like you do on the line below the commented one.
The most important problem is, when you do std::move(), your class member single is gone. It becomes empty unique_ptr (aka. std::unique_ptr{}, it doesn't manage anything). With any next call to getInstance, you're essentially returning nullptr. You should use std::shared_ptr, which you'll want to return by copy or return reference to your std::unique_ptr.
Even after making the getInstance static, it won't compile because the definition for destructor is missing. Either give empty definition or leave it as default.
~A() = default;
Moving single will work first time and invokes UB for subsequent calls to getInstance. Instead return by reference & and remove std::move
static std::unique_ptr<A>& getInstance(int log);
std::unique_ptr<A>& A::getInstance(int log)
{
if(!instanceFlag)
{
//single = std::make_unique<A>(log);
single = std::unique_ptr<A>(new A(log));
instanceFlag = true;
return single;
}
else
{
return single;
}
}
Inside main() you can get by reference
std::unique_ptr<A>& mA = A::getInstance(5);
The problem is that, as error log suggests, you are calling member function i.e. getInstance without any instance. Function std::unique_ptr<A> getInstance(int log); should be declared as static.
Declare it static as follow:
static std::unique_ptr<A> getInstance(int log);
Note: In singleton pattern getInstance function is always static function.
Following is an extract from Wikipedia:
An implementation of the singleton pattern must:
ensure that only one instance of the singleton class ever exists; and
provide global access to that instance.
Typically, this is done by:
declaring all constructors of the class to be private; and
providing a static method that returns a reference to the instance.
The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called.

Getting singleton instance inside its methods

I've got simple singleton class:
class Singleton
{
public:
static Singleton& getInstance()
{
static Singleton instance;
return instance;
}
// private constructor, etc...
}
The question is how should I access class instance from its member functions?
I've seen various code snippets and now I'm curious whether they have any significant differences.
1.
void Singleton::something(){
Singleton &self = getInstance();
self.doSomething();
}
2.
void Singleton::something(){
this->doSomething();
}
3.
void Singleton::something(){
doSomething();
}
is unnecessary complication - in a non-static member function like something we already have an instance, so there is no need to get it separately.
and 3. are the same, only 3. is shorter and more idiomatic - using this-> to access a member in C++ is not common.
I don't think there should be any other member function to get class instance except Singleton::getInstance();, because this is why it exist. Do it as below:
Sungleton &dst=Singleton::getInstance();
In fact, no way to get instance from non-static member function. When there is no class instance , how can you call its non-static member.

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.

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