C Singleton Example
In C , the Singleton pattern ensures that a class has only one instance throughout the program's execution. Here's an improved sample of a Singleton implementation:
<code class="cpp">class A { private: static A* m_pA; explicit A(); // Constructor should be private A(const A&) = delete; // Prevent copying A& operator=(const A&) = delete; // Prevent assignment virtual ~A(); // Destructor public: static A& GetInstance(); // Return a reference to the instance static void FreeInstance(); // Free the instance when no longer needed void WORK1(); void WORK2(); void WORK3(); }; A& A::GetInstance() { if (m_pA == nullptr) { static A instance; // Lazy initialization m_pA = &instance; } return *m_pA; // Return a reference to the instance } void A::FreeInstance() { delete m_pA; m_pA = nullptr; }</code>
Discussion:
Why Avoid Returning a Pointer?
The sample code provided initially returns a pointer to the Singleton instance. However, returning a reference is considered more suitable for Singletons because it prevents manual deallocation of the instance. The object's lifetime should be managed by the Singleton class itself.
Lazy Initialization:
The improved sample uses a static variable initialized by a function method to achieve lazy initialization. This technique ensures that the Singleton is created only when it is needed, improving efficiency.
Guaranteed Destruction:
By returning a reference, the Singleton ensures that the instance is not destroyed prematurely. It also takes care of proper destruction when the program exits, as the reference to the Singleton is automatically released.
Additional Notes:
The above is the detailed content of Why is Returning a Reference Preferred for C Singleton Implementation?. For more information, please follow other related articles on the PHP Chinese website!