c++11 单例模式

来源:互联网 发布:元江电视台软件 编辑:程序博客网 时间:2024/05/16 08:10
#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__

0 0