http://blog.csdn.net/hackbuteer1/article/details/7460019
考虑到线程安全、异常安全,可以做以下扩展
- class Lock
- {
- private:
- CCriticalSection m_cs;
- public:
- Lock(CCriticalSection cs) : m_cs(cs)
- {
- m_cs.Lock();
- }
- ~Lock()
- {
- m_cs.Unlock();
- }
- };
-
- class Singleton
- {
- private:
- Singleton();
- Singleton(const Singleton &);
- Singleton& operator = (const Singleton &);
-
- public:
- static Singleton *Instantialize();
- static Singleton *pInstance;
- static CCriticalSection cs;
- };
-
- Singleton* Singleton::pInstance = 0;
-
- Singleton* Singleton::Instantialize()
- {
- if(pInstance == NULL)
- {
- Lock lock(cs);
-
- if(pInstance == NULL)
- {
- pInstance = new Singleton();
- }
- } --》 //my注释:这里的lock类为局部变量,在这里会被析构,即会被解锁。
- return pInstance;
- }
【转】C++ 单例模式
原文:http://www.cnblogs.com/maxpak/p/4487437.html