zoukankan      html  css  js  c++  java
  • 饿汉模式单例模板

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

    •  析构私有,default_delete需要加入友元
    • 构造函数没有默认,有时候需要在构造函数里初始化数据
    #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()
    {
        static std::once_flag sflag;
        std::call_once(sflag, [&](){
            instance.reset(new T());
        });
        return *instance;
    }
    
    
    
    #define SINGLETON(Class)                           
    private:                                           
        ~Class() = default;                            
        Class(const Class &other) = delete;            
        Class& operator=(const Class &other) = delete; 
        friend class Singleton<Class>;                 
        friend struct std::default_delete<Class>;
    
    #endif // SINGLETON_H

    使用:

    #include "Singleton.h"
    
    #define Test_T Singleton<Test>::GetInstance()
    
    class Test
    {
        SINGLETON(LogMgr)
    private:
        Test() = default;    
    }
  • 相关阅读:
    20201224-3
    20201224-3 列表的使用1
    20201224 字符串常用操作
    20201224-1
    20201223-1 俄罗斯方块
    3月27日:毕业设计计划
    3月26日:毕业设计计划
    3月25日:毕业设计计划
    3月24日:毕业设计计划
    3月23日:毕业设计计划
  • 原文地址:https://www.cnblogs.com/vczf/p/12600251.html
Copyright © 2011-2022 走看看