Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destroying a singleton object

What is the best way to destroy a singleton object?

case A: Single threaded Environment
case B: Multi Threaded Environment

Sample snippets(if any) will be really helpful.

[EDIT] I don't have a specific use case I am just trying to understand that IF AT ALL the singleton has to be used how to destroy it correctly. As i understand, from the comments, there are 2 scenarios possible:
1. Destroy the singleton when no code is accessing it.(use smart pointers which will take care of destroying the object by itself using RAII)
2. Destroy a singleton when exiting the program irrespective of whether or not some code was holding on to the singleton. (explicitly destroy by deleting the instance just before main exits)

like image 357
Alok Save Avatar asked Dec 07 '22 01:12

Alok Save


1 Answers

Don't create it in the first place!

Seriously, I strongly recommend you reconsider your choice of singleton, especially in a multithreaded environment. Instead just create an instance in main() and pass it down the call hierarchy to where it is needed.

You can use something like shared_ptr to ensure that the object stays around until no-one needs it any more.

like image 68
Anthony Williams Avatar answered Dec 09 '22 14:12

Anthony Williams