Three C ++ singleton

Look at the following links: https://blog.csdn.net/zhanghuaichao/article/details/79459130

The following describes only the simplest kind of ways:

Introduction
        Since the design or development, certainly there will be such a situation, a class can have only one object is created, if there are multiple objects, it may lead to confusion and inconsistent state. In this case, Singleton is the most appropriate solution. There are many ways to achieve it, their characteristics are different, the situation is not the same use. Today was to be achieved three commonly used, are hungry Chinese-style, lazy type and multi-line programs.

        Single embodiment mode can be done:

1. Ensure that only one instance of a class is established 
2. Providing access to a global pointer to the object 
3. In the case the client does not affect the end singleton class allows multiple instances of the future

 

Lazy man
      lazy style is characterized by lazy loading, such as configuration files, using the lazy man's way, as the name suggests, it lazy, lazy, instance configuration file will be used until the time of loading. . . . . .

CSingleton class  
{  
public:  
static CSingleton the GetInstance * ()  
{  
     IF (m_pInstance == NULL)    
         m_pInstance new new CSingleton = ();  
     return m_pInstance;  
}  
Private:  
    CSingleton () {};  
    static CSingleton * m_pInstance;  
};
the GetInstance () using lazy initialization, which means it is the return value of this function for the first time when access is being created. This is a bullet-proof design - All calls the GetInstance () returns the same after the pointer instance:
CSingleton :: CSingleton the GetInstance = P1 * ();
CSingleton * P2 = P1-> the GetInstance ();
CSingleton REF = * & CSingleton :: GetInstance ();

GetInstance slightly modified for this design templates can apply to variable multi-instance cases, such as a class allows up to five instances.

Published 47 original articles · won praise 121 · views 680 000 +

Guess you like

Origin blog.csdn.net/guoyunfei123/article/details/105055962