1、单例用于频繁调用某些资源时,防止多次加载资源和释放资源,以下是单例的代码。
申明代码(.h)
#pragma once
class CSingleton
{
private:
CSingleton();//单例化
static CSingleton* m_pSingleton;//单例对象指针
static CCriticalSection m_limit;//临界量 用于限制多线程共通访问单例 导致出现同一时刻多出多个单例
class CRelease // 它的唯一工作就是在析构函数中删除CSingleton的实例
{
public:
~CRelease()//程序退出时进行析构
{
if (NULL != CSingleton::m_pSingleton)
{
delete CSingleton::m_pSingleton;
CSingleton::m_pSingleton = NULL;
}
}
};
static CRelease m_release;
public:
static CSingleton* GetInstance();//获取单例指针
};
定义代码(.cpp)
#include "StdAfx.h"
#include "Singleton.h"
CSingleton* CSingleton::m_pSingleton = NULL;
CCriticalSection CSingleton::m_limit;
CSingleton::CRelease CSingleton::m_release;
CSingleton::CSingleton()
{
}
CSingleton* CSingleton::GetInstance()
{
if (NULL == m_pSingleton)
{
m_limit.Lock();
if (NULL == m_pSingleton)
{
m_pSingleton = new CSingleton();
}
m_limit.Unlock();
}
return m_pSingleton;
}