单例实现
来源:互联网 发布:excel软件官方下载 编辑:程序博客网 时间:2024/05/20 23:39
#pragma once
#include <Windows.h>
#include <memory>
using namespace std;
class CResGuard {
public:
CResGuard() { m_lGrdCnt = 0; InitializeCriticalSection(&m_cs); }
~CResGuard() { DeleteCriticalSection(&m_cs); }
// IsGuarded is used for debugging
BOOL IsGuarded() const { return(m_lGrdCnt > 0); }
public:
class CGuard {
public:
CGuard(CResGuard& rg) : m_rg(rg) { m_rg.Guard(); };
~CGuard() { m_rg.Unguard(); }
private:
CResGuard& m_rg;
};
private:
void Guard() { EnterCriticalSection(&m_cs); m_lGrdCnt++; }
void Unguard() { m_lGrdCnt--; LeaveCriticalSection(&m_cs); }
// Guard/Unguard can only be accessed by the nested CGuard class.
friend class CResGuard::CGuard;
private:
CRITICAL_SECTION m_cs;
long m_lGrdCnt; // # of EnterCriticalSection calls
};
template <class T>
class Singleton
{
public:
static inline T* instance();
private:
Singleton(void){}
~Singleton(void){}
Singleton(const Singleton&){}
Singleton & operator= (const Singleton &){}
static auto_ptr<T> _instance;
static CResGuard _rs;
};
template <class T>
auto_ptr<T> Singleton<T>::_instance;
template <class T>
CResGuard Singleton<T>::_rs;
template <class T>
inline T* Singleton<T>::instance()
{
if( 0 == _instance.get() )
{
CResGuard::CGuard gd(_rs);
if( 0== _instance.get())
{
_instance.reset ( new T);
}
}
return _instance.get();
}
//Class that will implement the singleton mode,
//must use the macro in it's delare file
#define DECLARE_SINGLETON_CLASS(type)\
friend class auto_ptr<type>;\
friend class Singleton<type>;
- 单例模式实现
- 单例模式实现
- 单例实现
- dispatch_once 实现单例
- 单例实现方式
- 枚举实现单例
- JavaScript实现单例
- qt 实现单例
- c++单例实现
- 单例的实现
- C#实现单例
- 实现单例模式
- iOS实现单例
- python 单例实现
- C++单例实现
- 实现单例
- dispatch_once 实现单例
- 单例实现方式
- Ubuntu 下启用 Thinkpad 的指纹登录
- Linux环境变量的设置和查看方法
- Linux下的网络编程
- Python面向函数编程——装饰器的实际应用
- Multiple operations have reported errors Select an error to view its details
- 单例实现
- 点名系统
- java反射详解
- Spring框架的模块概要图及各模块功能简介
- 判断直线与矩形相交
- iOS开发:如何使用iOS手势UIGestureRecognizer
- Linux 备忘
- SerialPort comstat is being used without defining
- 在Eclipse平台中配置Tomcat