zoukankan      html  css  js  c++  java
  • Singleton模式笔记

    在C++中,尽量用Singleton替换全局变量是个很好的建议,Singleton一般如下:

    class  CSingleton
    {
    private:
        
    static CSingleton* m_pInstance;
    private:
        CSingleton(){}
        
    ~CSingleton(){}

        CSingleton( 
    const CSingleton& );
        CSingleton
    & operator=const CSingleton& );

    public:
        
    static CSingleton* GetInstance()
        {
            
    if( m_pInstance == NULL )
            {
                m_pInstance 
    = new CSingleton;
            }
            
    return m_pInstance;
        }
    };
    CSingleton
    *  CSingleton::m_pInstance = NULL;
    这种实现有个缺点:单例对象无法销毁.虽然泄漏的内存在程序结束后可由操作系统回收,但是会造成资源泄漏,如网络连接、COM引用等.这些操作系统是无法自动回收的.因此需要在程序结束前销毁这个单例对象.标准C库提供了一个很方便的函数:atexit,通过其注册的函数能在程序结束时自动调用(调用次序是后进先出),可以通过此函数实现单例对象的自动销毁功能:
    class  CSingleton
    {
    private:
        
    static CSingleton* m_pInstance;
    private:
        CSingleton(){}
        
    ~CSingleton(){}

        CSingleton( 
    const CSingleton& );
        CSingleton
    & operator=const CSingleton& );

    public:
        
    static CSingleton* GetInstance()
        {
            
    if( m_pInstance == NULL )
            {
                atexit( CSingleton::Destory );
                m_pInstance 
    = new CSingleton;
            }
            
    return m_pInstance;
        }

        
    static void Destory()
        {
            
    if( m_pInstance != NULL )
            {
                delete m_pInstance;
                m_pInstance  
    =  NULL;
            }
        }

    };
    CSingleton
    *  CSingleton::m_pInstance = NULL;

    Singleton模式的另一种实现,简称:Meyers 单件,其示例如下:

    class  CSingleton
    {
    private:
        CSingleton(){}
        
    ~CSingleton(){}

        CSingleton( 
    const CSingleton& );
        CSingleton
    & operator=const CSingleton& );

    public:
        
    static CSingleton& GetInstance()
        {
            
    static CSingleton instance;
            
    return instance;
        }
    };
  • 相关阅读:
    谈谈 rm -rf * 后的几点体会(年轻人得讲码德)
    shell读取文档中的命令并逐行执行
    被踢出工作群聊后的若干反思
    units命令单位转换
    想买保时捷的运维李先生学Java性能之 垃圾收集器
    想买保时捷的运维李先生学Java性能之 垃圾收集算法
    想买保时捷的运维李先生学Java性能之 生存与毁灭
    想买保时捷的运维李先生 求救求救求救求救
    想买保时捷的运维李先生学Java性能之 运行时数据区域
    想买保时捷的运维李先生学Java性能之 JIT即时编译器
  • 原文地址:https://www.cnblogs.com/fangkm/p/1486918.html
Copyright © 2011-2022 走看看