Singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
#include <mutex>
// 单例模式(Singleton Pattern):保证一个类仅有一个实例,并提供一个访问它的全局访问点。
class Singleton
{
public:
static Singleton * GetInstance();
static void ReleaseInstance();
private:
Singleton();
~Singleton();
private:
static Singleton * _ins;
static std::mutex _insMtx;
};
#endif // !SINGLETON_H
Singleton.cpp
#include "Singleton.h"
// 静态变量类外初始化
Singleton * Singleton::_ins = nullptr;
std::mutex Singleton::_insMtx = {};
#define DELETE(ptr) \
do \
{ \
if (ptr) \
{ \
delete ptr; \
ptr = nullptr; \
} \
} while(0)
Singleton * Singleton::GetInstance()
{
// 双重检查锁定模式(Double-Checked Locking Pattern, DCLP)
if (!_ins)
{
std::unique_lock<std::mutex> lck(_insMtx);
if (!_ins)
{
_ins = new Singleton();
}
}
return _ins;
}
void Singleton::ReleaseInstance()
{
std::unique_lock<std::mutex> lck(_insMtx);
DELETE(_ins);
}
Singleton::Singleton()
{
}
Singleton::~Singleton()
{
}