单例模式是最简单的创建型模式,当某个类只需要唯一的一份实例时,使用单例模式可以确保不会创建多余的实例。在C++ 中,单例模式可以避免全局变量的使用。下面是一个典型的线程安全的单例模式
#ifndef Singleton_h__
#define Singleton_h__
#include <mutex> //C++11
class CSingleton
{
public:
static CSingleton* GetInstance()
{
if (m_pInstance == NULL)
{
m_lock.lock();
//double check for better performance
if (m_pInstance == NULL)
{
m_pInstance = new CSingleton();
}
m_lock.unlock();
}
return m_pInstance;
}
static void Destroy()
{
m_lock.lock();
delete m_pInstance;
m_pInstance = NULL;
m_lock.unlock();
}
void Method()
{
//
}
private:
CSingleton(){}
~CSingleton()
{
delete m_pInstance;
m_pInstance = NULL;
}
//Disable copy and assign
CSingleton(const CSingleton& rhs);
CSingleton& operator = (const CSingleton& rhs);
private:
static CSingleton* m_pInstance;
static std::mutex m_lock;
};
CSingleton* CSingleton::m_pInstance = NULL;
std::mutex CSingleton::m_lock;
#endif // Singleton_h__
static CSingleton* GetInstance()
{
m_lock.lock();
if (m_pInstance == NULL)
{
m_pInstance = new CSingleton();
}
m_lock.unlock();
return m_pInstance;
}则每次调用GetInstance() 都需要加锁。
本文介绍了一种在C++中实现线程安全单例模式的方法,并通过双重检查锁定技术来提高性能。单例模式是一种创建型设计模式,用于确保某个类只有一个实例存在。
1539

被折叠的 条评论
为什么被折叠?



