a classOnly one object can be created, the design pattern of such a class is called the singleton pattern, which guaranteesin the systemthe classThere can only be one instance(andParent-child process sharing), a typical singleton class is the memory pool of C++STL
The basic design ideas of C++ singleton mode:
privatizationConstructor, delete the defaultcopy constructorandassignment operator overloadingPrevent objects from being created and copied directly
The memory resources of the singleton object can be released by the operating system, or the destructor can be customized to complete special operations
2. Two implementations of singleton mode
hungry man mode
Hungry singleton class in the programbefore entering the main functioncreates a unique instance of
HungerSingletonofstatic member variableyesan object (or pointer) of its own type,Categorystatic member variableThe initialization is completed before entering the main function. Since the constructor is privatized, objects of this class cannot be created during the running of the program.
Advantages of Hungry Singleton Mode:
becauseChild processes can only be created in the main function, so the singleton classThere are no thread safety issues, without competing for system resources with classes of other threads, inIn a multi-threaded high-concurrency environmentAble to perform tasks more efficiently
Disadvantages of the Hungry Singleton Pattern:
If there are multiple singleton classes in a program, weno control over their initialization order
The hungry singleton class will slow down the startup speed of the program, and even if the class is not used, an instance will be created, which may cause memory waste
lazy mode
lazy singleton class in the programAfter entering the main functionIt is up to subsequent code to decide whether to create an instance