标签:
单例模式(Singleton),保证一个类仅有一个实例。
多线程下的单例模式:Double-Check Locking(双重锁定),既避免了多次加锁解锁,也保证了线程安全
#include <iostream> using namespace std; class Singleton { public: static Singleton *GetInstance() { if (m_Instance == NULL ) { Lock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明 if (m_Instance == NULL ) { m_Instance = new Singleton (); } UnLock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明 } return m_Instance; } static void DestoryInstance() { if (m_Instance != NULL ) { delete m_Instance; m_Instance = NULL ; } } int GetTest() { return m_Test; } private: Singleton(){ m_Test = 0; } static Singleton *m_Instance; int m_Test; }; Singleton *Singleton ::m_Instance = NULL; int main(int argc , char *argv []) { Singleton *singletonObj = Singleton ::GetInstance(); cout<<singletonObj->GetTest()<<endl; Singleton ::DestoryInstance(); return 0; }
标签:
原文地址:http://www.cnblogs.com/whutqueqiaoxian/p/4820985.html