Automatic destruction of instances in singleton mode of C++ design mode (automatic garbage collector)
With regard to the destruction of m_pinstance pointing to space in C++ singleton mode, manual destruction of m_pInstance is often a headache, and memory and resource leaks are also common. Can there be a method to allow instances to be released automatically.
The solution is to define an internal garbage collection class and define a static member of this class in Singleton. At the end of the program, the system will automatically destruct the static member. At this time, destructing the Singleton instance in the destructor of this class can realize the automatic release of m_pInstance.
Attach the test code
1 # include 2 using namespace std; 3 4 class Singleton 5 {6 public: 7 static Singleton * GetInstance () 8 {9 if (m_Instance = = NULL) 10 {11 m_Instance = new Singleton (); 12 cout