您的位置:首页 > 编程语言 > C语言/C++

c++11 单例模式

2015-12-01 00:37 561 查看
#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__
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: