Reflection on Singleton

zhaozj2021-02-16  64

Singleton is the easiest mode, this article describes the problems and reflections encountered by small chickens.

For Singleton, the chick shot can not: 1. Declare the private static member variable as a Singleton class? 2. The way to call directly is Static?

In the project, use VC to implement the Singleton class, compile, and link everything OK. There is a memory Exception, and the debug is found: Static member variables are not initialized! It turned out to call another Singleton class in a Singleton constructor, and another Singleton class has not been initialized. So, method 1 is used, when multiple Singleton classes are called intercom in the constructor, an error may occur. The same is true for 2, and if another Singleton's static method is called in a Singleton constructor, there will be problems caused by the initial sequence factors. In addition, the method 2 has a defect that the Singleton cannot be passed as a parameter.

Conclusion: - or the Singleton is implemented as a pointer to the Static Singleton class - in order to avoid Memory Leak, you can add packaging classes similar to Auto_PTR.

转载请注明原文地址:https://www.9cbs.com/read-16521.html

New Post(0)