单例模式
使用单例模式的目的是使得类在系统中的仅有一个实例
代码实现
#include <mutex>
template<typename T>
class Sington
{
protected:
Sington() {}
virtual ~Sington() {}
public:
template<typename... Args>
static T* Instance(Arg&&... arg)
{
if (!sInstance)
{
std::lock_guard<std::mutex> guard(mMutex);
if (!sInstance)
{
sInstance = new T(std::forward<Args>(args)...);
static GCInstance mGCInstance;
}
}
return sInstance;
}
private:
class GCInstance
{
public:
GCInstance() = default;
~GCInstance()
{
if (Sington::sInstance)
{
delete Sington::sInstance;
Sington::sInstance = nullptr;
}
}
friend class Sington;
};
private:
static T* sInstance;
static std::mutex mMutex;
};
template<typename T>
T* Sington<T>::sInstance = nullptr;
template<typename T>
std::mutex Sington<T>::mMutex;
使用
1、将ClassA构造函数私有化;
2、在ClassA中声明friend Sington<ClassA>;
3、使用Sington<ClassA>::Instance();构造ClassA的唯一实例
问题及缺陷
1、Windows vs2019使用中发现,在每个dll中都会构造一个实例(未找到解决方法);若不使用模板,不会出现这种情况(即在ClassA中使用单例模式);
2、指令的重排序,可能导致错误;(概率极低,在自己是工作场景中近乎不可能,故未处理)