C++单例模式的实现

来源:互联网 发布:笔记本网卡mac地址修改 编辑:程序博客网 时间:2024/06/14 12:45
#ifndef SINGLETON_H
#define SINGLETON_H


#include <iostream>  
#include <memory>  
#include <mutex> 
using namespace std;


namespace Common 
{
template <class T>
class  CSingleton
{
public:
static inline T* Instance();
private:
CSingleton(void) {}
~CSingleton(void) {}


CSingleton(const CSingleton&) {}
CSingleton & operator= (const CSingleton &) {}


static auto_ptr<T> _instance;
static std::mutex _mutex;
//static CQuickLock _rs;
};


template <class T>
auto_ptr<T> CSingleton<T>::_instance;


template <class T>
std::mutex CSingleton<T>::_mutex;






template <class T>
inline T* CSingleton<T>::Instance()
{


if (0 == _instance.get())
{
//上锁,防止多线程可能创建多个Singleton实例
std::lock_guard<std::mutex> lock(_mutex);


if (0 == _instance.get())
{
_instance.reset(new T);
}


}


return _instance.get();
}
}




/////////////////Singleton应用实例
class  CMyLog 
{
friend class auto_ptr<CMyLog>;              //作为友元可以访问CMyLog的私有成员
friend class Common::CSingleton<CMyLog>;     //作为友元可以访问CMyLog的私有成员 
public:
void Log(char* pszStr)
{
cout << "Log msg: " << pszStr << endl;
}


public:
int a;


private:
int b;

CMyLog() {};               //不允许直接实例化
virtual ~CMyLog(void) {};
};






int main()
{
CMyLog* pLog = Common::CSingleton<CMyLog>::Instance();
pLog->Log("hello word");
pLog->a = 10;

CMyLog* pLog1 = Common::CSingleton<CMyLog>::Instance();
int b = pLog->a;




system("pause");
return 0;
}
#endif/*SINGLETON_H*/