单例模式

懒汉模式

lazy load,只有在使用的时候才会进行初始化

class CSingleton  
{  
private:  
   CSingleton(){} 
   static CSingleton *m_pInstance;  
public:  
   static CSingleton * GetInstance()  
   {  
       if(m_pInstance == NULL) 
           m_pInstance = new CSingleton();  
       return m_pInstance;  
   }  
};  

改进1

懒汉模式中m_pInstance指向的空间没有得到释放,利用程序在结束时自动析构全局变量以及所有的类的静态成员变量特性,在单例类中添加内存回收的类

class CSingleton  
{  
private:  
   CSingleton(){}  
   static CSingleton *m_pInstance;  
   class CGarbo  
   {  
   public:  
       ~CGarbo()  
       {  
           if(CSingleton::m_pInstance)  
               delete CSingleton::m_pInstance;  
       }  
   };  
   static CGarbo Garbo; 
public:  
   static CSingleton * GetInstance()  
   {  
       if(m_pInstance == NULL)  
           m_pInstance = new CSingleton();  
       return m_pInstance;  
   }  
};  

改进2

懒汉模式不是线程安全,考虑双重加锁,

static CCriticalSection cs;  
static CSingleton * GetInstance()  
{  
  if(m_pInstance == NULL) 
  { 
        Lock lock(cs);  
        if(m_pInstance == NULL)
        m_pInstance = new CSingleton();  
  }
  return m_pInstance;  
}  

饿汉模式

加载之初就将自己实例化,因此是线程安全的

class CSingleton  
{  
private:  
    static CSingleton *m_pInstance = new CSingleton();
    CSingleton(){}  
public:  
    static CSingleton * GetInstance()  
    {    
        return instance;  
    }  
};  

无锁的线程安全的懒汉形式

将返回的实例对象定义成GetInstance函数的静态局部变量

class Singleton
{
public:
    static Singleton* GetInstance()
    {
        static Singleton *instance = new Singleton();
        //cout << instance << endl;
        return instance;
    }
private:
    Singleton(){}
};

PS:NS3中采用此方法实现单例模板

template <typename T>
class Singleton : private NonCopyable
{
public:
  static T *Get (void) {
   static T object;
   return &object;
};

原文地址:https://www.cnblogs.com/rainySue/p/dan-li-mo-shi.html