Wednesday, 5 September 2018

Singleton: Destructor should be private or public?


We make sure that one instance of class is created by making constructor private. How do we release/destroy the instance?

Query : Should we delete the instance in destructor?

Response : Not in the traditional way.

The destructor will look like this

Single :: ~Single()
{
    delete instance;
}

When the 'delete instance' is called it will invoke the destructor for the instance and it will keep running in an infinite loop.

Query : When to release the Singleton Class Instance?

Response : Singleton instance is supposed to be there for the complete lifetime of the program. Once the program finishes, C++ automatically deletes static objects. However, it is recommended to write a release function to make sure to release the memory when program ends. The problem is with multiple user/thread accessing the Singleton. To make sure it ends properly have a private variable "count" of number of users having access to the class.

Single* Single::getInstance()
{
 if(!instance)
 {
  instance = new Single();
 }
    ++count;
 return instance;
}

void Single::releaseInstace()
{
    --count;
    if((count==0) && (instance!=NULL))
    {
        delete instance;
        instance=NULL;
    }
}

Note: This doesn't work if a particular user calls multiple get instance of the class but deletes only once. Also, calling releaseInstance() multiple times by same user will also lead to situation where instance is deleted while it is used by another user.

Query : Should Destructor be private or public?

Response : It is recommended to keep private destructor and a public static function to release instance as mentioned above.




Back to Singleton

No comments:

Post a Comment

Singleton : Is it Thread Safe?

Singleton is not thread-safe in C++. Query : How does multiple threads affects Singleton? Response : Lets assume that no instance of...