Home > Article > Backend Development > When Should You Return a Singleton as a Reference in C ?
Singleton Pattern in C
This question seeks a practical example of the Singleton pattern in C . In the context of the Singleton pattern, it's important to note the common practice of returning a singleton instance as a pointer. However, an alternative approach is to return a reference instead.
Returning a Singleton as a Reference
The question highlights the logic of returning a singleton as a reference instead of a pointer. This ensures that the singleton cannot be manually freed, as unknown clients may still hold references to it.
Lazy Initialization Using Static Functions
The example provided demonstrates lazy initialization of the singleton using a static method:
<code class="cpp">class S { public: static S& getInstance() { static S instance; return instance; } private: S() {} S(const S&); // Don't Implement. void operator=(const S&); // Don't implement };</code>
This approach guarantees single creation and destruction as well as lazy initialization.
Additional Considerations
The author provides additional insights for implementing Singletons effectively:
The above is the detailed content of When Should You Return a Singleton as a Reference in C ?. For more information, please follow other related articles on the PHP Chinese website!