赞
踩
利用unique_lock互斥锁实现,lock_guard亦可。
std::unique_lock 与std::lock_guard都能实现自动加锁与解锁功能,但是std::unique_lock要比std::lock_guard更灵活,但是更灵活的代价是占用空间相对更大一点且相对更慢一点。
废话不多说直接上代码
以下是头文件内容
public:
~Singleton();
static Singleton* GetInstance();
static void DestoryInstance();
private:
Singleton();
static Singleton* m_Singleton;
static std::mutex m_mutex;
以下是CPP内容
Singleton* Singleton::m_Singleton; std::mutex Singleton::m_mutex; Singleton::Singleton() { } Singleton::~Singleton() { } Singleton* Singleton::GetInstance() { if (m_Singleton == nullptr) { std::unique_lock<std::mutex> lock(m_mutex); if (m_Singleton == nullptr) { m_Singleton = new Singleton(); } } return m_Singleton; } void Singleton::DestoryInstance() { delete m_Singleton; m_Singleton = nullptr; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。