Code for C++ delete singleton instance

(Last Updated On: February 25, 2019)

Answer:To delete singleton instance or object in C++ programs, we need to follow a proper design to delete singleton object in the class . Especially, when multiple users are using object of singleton class in c++ program. One of the bad situations we can think that what if one user has deleted singleton object while other multiple users are still using the single instance.

So, one of the designs we can follow is “Reference counting” mechanism to delete singleton instance of a class in C++ program. Whenever, a user requests an instance to single class, we can increase the reference count and when he delete it we can decrease the reference count.

And deletion of singleton class object would be allow only when the count is zero.

To design C++ delete singleton instance, first, we need to make the singleton class destructor private, so, it can not be accessed from outside of the class. Hence, user cannot delete the singleton instance using the keyword “delete”.  Also, we have to introduce a static method in the singleton class, say “releaseInstance() that will be used to delete singleton class pointer.

Introduce a new static variable “count” that will be used to track users. And, also, have two other private method “addRef()” and “releasRef()” to increase and decrease counts of the instance.

Whenever, releaseInstance() function is called, this function will check if singleton class object destruction is required or not.

C++ delete singleton instance design

C++ Code Example


Note that this question can also be asked as to provide c++ singleton destructor example. Hence, the answer should be same as above that we need to make custom design to delete instance of singleton class.