// 单例模板类:
template<class T>
class MSingleton
{
private:
MSingleton() = default;
~MSingleton() = default;
MSingleton(const MSingleton&) = delete;
MSingleton& operator=(const MSingleton&) = delete;
public:
static T* getInstance()
{
try
{
if (_instance == nullptr)
{
std::unique_lock<std::mutex> lock(_mtx);
if (_instance == nullptr)
{
_instance = new T;
}
}
return _instance;
}
catch (...)
{
return nullptr;
}
}
private:
static MSingleton* _instance = nullptr;
static std::mutex _mtx;
};
// 带参数创建:
template<class...Args>
static T* getInstance(Args...args)
{
try
{
if (_instance == nullptr)
{
std::unique_lock<std::mutex> lock(mtx);
if (_instance == nullptr)
{
_instance = new T(args...);
}
}
return _instance;
}
catch(...)
{
return nullptr;
}
}
单例模式升级版
于 2022-06-17 11:25:28 首次发布