I started working on a system modeling project a couple of weeks ago and have run into a situation where I believe I may need to use a Singleton Class, albeit, I could do with global variables too. But I want to learn and understand Singletons.
Anywho .. I am trying to understand a Singleton class, specifically, when is the destructor called ? Since the point of a Singleton class is to create and sustain a single instance of the class over the entire run across multiple threads, how does the compiler accurately figure out when to destroy the instance, without any of the threads explicitly calling the destructor (which they cant, since in most implementations, the destructor is private)?
It depends on how you implement the singleton. If the instance is a local static variable inside the function or a static member of the class it will be automatically destroyed when the program ends. If the instance was created with new and stored as a regular pointer it will not be destroyed unless you explicitly call delete (this may or may not be a problem).