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

    //饿汉模式:即类产生的时候就创建好实例对象,这是一种空间换时间的方式
    class CSingleton
    {
    public:
        ~CSingleton() {};
        CSingleton(const CSingleton&);
        CSingleton& operator=(const CSingleton&);
        static CSingleton& GetInstance()
        {        
            return instance;
        }
    private:
        CSingleton() {};
        static CSingleton instance;
    };
    
    //懒汉模式:即在需要的时候,才创建对象,这是一种时间换空间的方式
    class CSingleton
    {
    public:
        ~CSingleton(){};
        CSingleton(const CSingleton&);
        CSingleton& operator=(const CSingleton&);
        static CSingleton& GetInstance()
        {
            static CSingleton instance;
            return instance;
        }
    private:
        CSingleton(){};
    
    };
    
    //双层锁的方式
    class CSingleton
    {
    public:
        ~CSingleton() {};
        static CSingleton* GetInstance()
        {
            if (m_pInstance == nullptr)
            {
                std::lock_guard<std::mutex> lck(m_mutex);
                if (m_pInstance == nullptr)
                {
                    m_pInstance = new CSingleton;   //内存存在泄漏,可替换智能指针方式
                }
                return m_pInstance;
            }
        }
    private:
        CSingleton() {};
        static CSingleton* m_pInstance;
        static std::mutex m_mutex;
    };
    
    //智能指针方式
    class CSingleton
    {
    public:
        ~CSingleton() {};    //注意智能指针shared_ptr无法访问私有化的析构函数,若析构函数定义为private,则在单例类内部再定义一个静态的Destory函数,在定义share_ptr的时候指定删除器为destroy
        static std::shared_ptr<CSingleton> GetInstance()
        {
            if (m_pInstance == nullptr)
            {
                std::lock_guard<std::mutex> lck(m_mutex);
                if (m_pInstance == nullptr)
                {
                    m_pInstance = std::shared_ptr<CSingleton>(new CSingleton);
                }
                return m_pInstance;
            }
        }
    private:
        CSingleton() {};
        static std::shared_ptr<CSingleton> m_pInstance;
        static std::mutex m_mutex;
    };
  • 相关阅读:
    MySql日期与时间函数
    Redis内存分析工具redis-rdb-tools
    MYSQL5.7脚本运行时出现[Warning] Using a password on the command line interface can be insecure
    Prometheus
    Shopt命令(删除排除)
    Nginx配置跨域支持功能
    Nginx之 try_files 指令
    Grafana使用阿里云短信的报警实现
    用python发送短消息(基于阿里云平台)
    同步pod时区与node主机保持一致
  • 原文地址:https://www.cnblogs.com/yapp/p/14307174.html
Copyright © 2011-2022 走看看