首页 > 其他 > 详细

饿汉模式单例模板

时间:2020-03-30 18:45:27      阅读:69      评论:0      收藏:0      [点我收藏+]

使用c11的std::call_once实现饿汉模式的单例模板

 

#ifndef SINGLETON_H
#define SINGLETON_H
#include <memory>
#include <mutex>

//单例模板

template <typename T>
class Singleton {
public:
    static T& GetInstance();

private:
    static std::unique_ptr<T> instance;
};

template <typename T>
std::unique_ptr<T> Singleton<T>::instance;

template <typename T>
T& Singleton<T>::GetInstance()
{
    std::once_flag sflag;
    std::call_once(sflag, [&](){
        instance.reset(new T());
    });
    return *instance;
}



#define SINGLETON(Class)                           public:                                                ~Class() = default;                            private:                                               Class() = default;                                 Class(const Class &other) = delete;                Class& operator=(const Class &other) = delete;     friend class Singleton<Class>;                 
#endif // SINGLETON_H

 

饿汉模式单例模板

原文:https://www.cnblogs.com/vczf/p/12600251.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!