If there are necessary operations in the destruction behavior of the class, such as closing the file and releasing external resources, then the above code cannot achieve this requirement. We need a way to delete the instance normally.
You can call GetInstance() at the end of the program and use the delete operation for the returned pointer. Doing so can achieve functionality, but it is not only ugly, but also error-prone. Because such additional code is easy to forget, and it is difficult to ensure that after delete, there is no code to call the GetInstance function.
A proper wayIt is to let this class know to delete itself when it is appropriate, or to hang the operation of deleting itself on a suitable point in the operating system so that it will be automatically executed at the appropriate time.
We know that when the program ends, the system willAutomatically destruct all global variables. In fact, the system will also destruct static member variables of all classes, just as these static members are global variables. Using this feature, we can define such a static member variable in a singleton class, and its only job is to delete instances of the singleton class in the destructor. For example, the CGarbo class in the following code (Garbo means garbage worker):
class CSingleton
{
//Other members
public:
static CSingleton* GetInstance();
private:
CSingleton(){};
static CSingleton * m_pInstance;
class CGarbo //Its only job is to delete the instance of CSingleton in the destructor
{
public:
~CGarbo()
{
if( CSingleton::m_pInstance )
delete CSingleton::m_pInstance;
}
}
Static CGabor Garbo; //Define a static member. When the program ends, the system will automatically call its destructor.
};
Class CGarbo is defined as a private inline class of CSingleton in case the class is abused elsewhere.
When the program runs, the system calls the destructor of Garbo, a static member of CSingleton, which deletes the unique instance of the singleton.
Releasing a singleton object using this method has the following characteristics:
Define proprietary nested classes inside singleton classes;
Define private static members that are specifically used for release within a singleton class;
Use the program to destruct the characteristics of global variables at the end to select the final release time;
Code that uses singletons requires no operation and does not have to care about the release of objects.
The specific code is as follows: