上一篇关于单例模式的实现 主要是Doubke-Check Locking。
但是多线程环境下并不能保证完全线程安全。
这篇文章实现的单例:
懒汉模式 的单例
基于模板和继承
线程安全
使用智能指针 防止内存泄露
效率相对较高
实现代码如下:
#include <iostream>
#include <memory>
#include <windows.h>
#include <process.h>
using namespace std;
template <class T>
class CSingletonPtr
{
// 私有删除器
private:
class Deleter
{
public:
// 重载()操作符
void operator()(T* p)
{
delete p;
}
};
private:
static tr1::shared_ptr<T> m_pInstance; // 智能指针 避免内存泄露
private:
CSingletonPtr(const CSingletonPtr&){}
CSingletonPtr& operator=(const CSingletonPtr&){}
protected:
// 需要继承 所以一定要声明为public
CSingletonPtr()
{
cout << "CSingletonPtr begin construct" << endl;
::Sleep(1000);
cout << "CSing