Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report