#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <thread>
#include <memory>
#include <mutex>
#include <exception>
template<typename T>
class Singleton
{
public:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton &) = delete;
Singleton(Singleton &&) = delete;
Singleton &operator=(const Singleton &) = delete;
Singleton &operator=(Singleton &&) = delete;
template<typename ...Args>
static void make_shared_instance(Args&&...args)
{
if (instance)
{
throw std::runtime_error("instance is already make.");
}
instance= std::make_shared<T>(std::forward<Args>(args)...);
}
template<typename ...Args>
static std::shared_ptr<T> makeInstance(Args&& ... args)
{
std::call_once(flag, make_shared_instance<Args...>, std::forward<Args>(args)...);
return instance;
}
template<typename ...Args>
static std::shared_ptr<T> Instance()
{
if (instance)
{
return instance;
}
throw std::runtime_error("instance is not make.");
}
private:
static std::once_flag flag;
static std::shared_ptr<T> instance;
};
template<typename T>
std::once_flag Singleton<T>::flag;
template<typename T>
std::shared_ptr<T> Singleton<T>::instance;
#endif//__SINGLETON_H__
c++11 单例模式
最新推荐文章于 2023-03-10 23:09:12 发布