Home >Backend Development >C++ >How to Achieve Proper Memory Management in C Singleton Implementation?
Singleton Pattern in C with Proper Memory Management
The Singleton pattern ensures that only one instance of a class can be created. While many approaches exist, a common practice is to use a static pointer to manage the instance creation and destruction. However, it's crucial to adhere to memory management rules to prevent errors.
In this example:
<code class="cpp">class A { static A* m_pA; A(); ~A(); static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); }; A* A::GetInstance() { if (m_pA == NULL) m_pA = new A(); return m_pA; } A::~A() { FreeInstance() // Don't write this here } void A::FreeInstance() { delete m_pA; m_pA = NULL; }</code>
Manually freeing a singleton using the destructor is incorrect. If external references to the instance exist, deleting it prematurely will lead to crashes.
Instead, adopt a better approach:
<code class="cpp">class A { static A* m_pA; explicit A(); void A(const A& a); void A(A &a); const A& operator=(const A& a); ~A(); static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); }; A* A::GetInstance() { if (m_pA == NULL){ static A self; m_pA = &self; } return m_pA; } A::~A() { }</code>
Here, the static instance is created and destroyed automatically by the compiler, ensuring proper memory management. Additionally, mark the constructor as explicit to prevent implicit type conversions and make the copy constructor and assignment operator private to prohibit undesired object duplication.
The above is the detailed content of How to Achieve Proper Memory Management in C Singleton Implementation?. For more information, please follow other related articles on the PHP Chinese website!