what is the exact use and implementation of singleton class? - c++

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!

Related

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.

Use of public destructor when the constructor is private

I have seen code where the constructor has been declared as private while the destructor is public. What is the use of such a declaration? Is the destructor required to be public so that during inheritance the calls can be possible or is it a bug in the code?
The question might seem to be a bit short on information, but what I really want to know is if having a public destructor when the constructor is required to be private abides by the C++ rules?
Short Answer
Creating a constructor as private but the destructor as public has many practical uses.
You can use this paradigm to:
Enforcing reference counting (See Hitesh Vaghani's example).
Implement the singleton pattern
Implement the factory pattern.
Long Answer
Above I hinted that you can use private constructors and destructors to implement several design patterns. Well, here's how...
Reference Counting
Using private destructor within an object lends itself to a reference counting system. This lets the developer have stronger control of an objects lifetime.
class MyReferenceObject
{
public:
static MyReferenceObject* Create()
{
return new MyReferenceObject();
}
void retain()
{
m_ref_count++;
}
void release()
{
m_ref_count--;
if (m_ref_count <= 0)
{
// Perform any resource/sub object cleanup.
// Delete myself.
delete this; // Dangerous example but demonstrates the principle.
}
}
private:
int m_ref_count;
MyReferenceObject()
{
m_ref_count = 1;
}
~MyReferenceObject() { }
}
int main()
{
new MyReferenceObject(); // Illegal.
MyReferenceObject object; // Illegal, cannot be made on stack as destructor is private.
MyReferenceObject* object = MyReferenceObject::Create(); // Creates a new instance of 'MyReferenceObject' with reference count.
object->retain(); // Reference count of 2.
object->release(); // Reference count of 1.
object->release(); // Reference count of 0, object deletes itself from the heap.
}
This demonstrates how an object can manage itself and prevent developers from corrupting the memory system. Note that this is a dangerous example as MyReferenceObject deletes itself, see here for a list of things to consider when doing this.
Singleton
A major advantage to private constructors and destructors within a singleton class is that enforces the user to use it in only the manner that the code was design. A rogue singleton object can't be created (because it's enforced at compile time) and the user can't delete the singleton instance (again, enforced at compile time).
For example:
class MySingleton
{
public:
MySingleton* Instance()
{
static MySingleton* instance = NULL;
if (!instance)
{
instance = new MySingleton();
}
return instance;
}
private:
MySingleton() { }
~MySingleton() { }
}
int main()
{
new MySingleton(); // Illegal
delete MySingleton::Instance(); // Illegal.
}
See how it is almost impossible for the code to be misused. The proper use of the MySingleton is enforce at compile time, thus ensuring that developers must use MySingleton as intended.
Factory
Using private constructors within the factory design pattern is an important mechanism to enforce the use of only the factory to create objects.
For example:
class MyFactoryObject
{
public:
protected:
friend class MyFactory; // Allows the object factory to create instances of MyFactoryObject
MyFactoryObject() {} // Can only be created by itself or a friend class (MyFactory).
}
class MyFactory
{
public:
static MyFactoryObject* MakeObject()
{
// You can perform any MyFactoryObject specific initialisation here and it will carry through to wherever the factory method is invoked.
return new MyFactoryObject();
}
}
int main()
{
new MyFactoryObject(); // Illegal.
MyFactory::MakeObject(); // Legal, enforces the developer to make MyFactoryObject only through MyFactory.
}
This is powerful as it hides the creation of MyFactoryObject from the developer. You can use the factory method to perform any initilisation for MyFactoryObject (eg: setting a GUID, registering into a DB) and anywhere the factory method is used, that initilisation code will also take place.
Summary
This is just a few examples of how you can use private constructors and destructors to enforce the correct use of your API. If you want to get tricky, you can combine all these design patterns as well ;)
First thing: the destructor can be private.
having a public destructor when the constructor is required to be
private abides by the C++ rules?
It's totally working in C++. In fact, a great example of this scenario is the singleton pattern, where the constructor is private and the destructor is public.
In reverse order.
Is the destructor required to be public so that during inheritance the calls can be possible or is it a bug in the code?
Actually, for inheritance to work the destructor should be at least protected. If you inherit from a class with a private destructor, then no destructor can be generated for the derived class, which actually prevents instantiation (you can still use static methods and attributes).
What is the use of such declaration?
Note that even though the constructor is private, without further indication the class has a (default generated) public copy constructor and copy assignment operator. This pattern occurs frequently with:
the named constructor idiom
a factory
Example of named constructor idiom:
class Angle {
public:
static Angle FromDegrees(double d);
static Angle FromRadian(double d);
private:
Angle(double x): _value(x) {}
double _value;
};
Because it is ambiguous whether x should be precised in degrees or radians (or whatever), the constructor is made private and named method are provided. This way, usage makes units obvious:
Angle a = Angle::FromDegrees(360);
You make constructor private if you want to prevent creating more then one instance of your class. That way you control the creation of intances not their destruction. Thus, the destructor may be public.
One example in my head, let's say you want to limit the class instance number to be 0 or 1.
For example, for some singleton class, you want the application can temprary destroy the object to rducue memory usage. to implement this constructor will be private, but destructor will be public. see following code snippet.
class SingletoneBigMemoryConsumer
{
private:
SingletoneBigMemoryConsumer()
{
// Allocate a lot of resource here.
}
public:
static SingletoneBigMemoryConsumer* getInstance()
{
if (instance != NULL)
return instance;
else
return new SingletoneBigMemoryConsumer();
}
~SingletoneBigMemoryConsumer()
{
// release the allocated resource.
instance = NULL;
}
private:
// data memeber.
static SingletoneBigMemoryConsumer* instance;
}
//Usage.
SingletoneBigMemoryConsumer* obj = SingletoneBigMemoryConsumer::getInstance();
// You cannot create more SingletoneBigMemoryConsumer here.
// After 1 seconds usage, delete it to reduce memory usage.
delete obj;
// You can create an new one when needed later
The owner of an object needs access to the destructor to destroy it. If the constuctors are private, there must be some accessible function to create an object. If that function transferes the ownership of the constructed object to the caller ( for example return a pointer to a object on the free store ) the caller must have the right to access the destructor when he decides to delete the object.

How to automatically maintain a list of class instances?

In my C++ project, I have an Engine class and an Object class.
My issue lies with how my instances of Object are created. Currently this is done through the use of a CreateObject(parameters) function in the Engine class. This adds a new instance of Object to an std::vector of Object instances.
I want to maintain this list of instances of Object in my Engine class, but without the need for the CreateObject(parameters) function. My reason for this is so that I can create new classes that can inherit from Object but still be added to this list. The reason for this list is so that (in Engine) I can iterate through every Object instance that has been created.
This would ultimately mean that I create my Object instances with something like Object newObject = Object(parameters);, but still have the Engine class maintain a list of all Object instances, without the need for Object to reference the instance of Engine or the list to add itself to this list (as in the instance of Object should not know about the list it is in). Can this be done?
You can define a static collection data member in your Engine class, update it in your Object constructor and destructor:
class Engine
{
friend class Object;
...
public:
static std::set< Object* > m_instances;
};
class Object
{
public:
Object();
virtual ~Object();
...
};
You increment it in constructors, and decrement it in destructors.
Object::Object()
{
Engine::m_instances.insert(this);
}
Object::~Object()
{
Engine::m_instances.erase(this);
}
I think your factory pattern approach is the good way to achieve this. The engine manages all the instances of Objects internally.
But if you want to make external instances, managed by the engine too, you must have to access a instance of the engine; even if that instance is a global variable, even if the Engine class implements a singleton pattern.
The second best approach to do that (The first is what yoa are doint yet, the factory), I think is to implement a singleton in the Engine:
class Object
{
Object
{
Engine::instance().addObject( this ); //Note that engine stores pointers. STL containers cannot store references.
}
~Object
{
Engine::instance().releaseObject( this );
}
};
Use a static
vector<Object*> Objects
variable in Engine class and static public function
Push(Object* obj) { Objects.push_back(obj); }
to push Objects to the list. Then in constructor of your Object class you would call
Engine::Push(this)
Like many have mentioned, factory architecture is a nice and clean way to go, otherwise you are going to have to have a global instance, static members or a singleton. However, a static approach would be to
make Object a friend of class engine and make the members static:
class Engine{
friend class Object;
private:
static std::vector <Object*> objectList;
};
This will allow Object to access private members of Engine statically. Then in the constructor of Object, add it to the list like so:
Object::Object(int randomparam1, const char* randomparam2)
{
Engine::objectList.push_back(this);
}

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

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