1.双重检查锁
mutex mt;
class Singleton
{
private:
Singleton(){};
Singleton(const Singleton& rhs) = delete;
Singleton& operator=(const Singleton& rhs) = delete;
static Singleton* m_instance;
public:
static Singleton* instance()
{
if(m_instance == nullptr)
{
mt.lock();
if(m_instance == nullptr)
m_instance = new Singleton();
mt.unlock();
}
return m_instance;
}
};
Singleton* Singleton::m_instance = nullptr;
2.局部静态变量
class singleton
{
public:
static singleton& getInstance()
{
static singleton m_instance;
return m_instance;
}
private:
singleton(){};
singleton(const singleton& rhs) = delete;
singleton& operator=(const singleton& rhs) = delete;
};
|