单例模式保证一个类仅有一个实例,并提供一个访问它的全局访问点。
单例模式非常简单,在开发中经常遇到,比如读写配置文件的类等。
代码如下:
//单例类
class Singleton
{
private:
static Singleton* m_pInstance;
Singleton() {}
~Singleton() {}
public:
static Singleton* GetInstance()
{
std::mutex mt;
if ( m_pInstance == NULL)
{
mt.lock();
if (m_pInstance == NULL)
{
m_pInstance = new Singleton();
}
mt.unlock();
}
return m_pInstance;
}
};
这里用了c++std标准库中的mutex,使用lock unlock防止多线程实例化,也叫双重锁定。