Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Automatic destruction of instances in singleton mode of C++ design mode (automatic garbage collector)

Shulou Source: shulou.com Published: 2022-06-01 08:42:59 09月14日 Update

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

Tags: Members static garbage programs instances methods problems runs patterns important headaches common code information memory functions that is manual pointing space Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Linux Redmi NVidia Huawei