• 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;
        }
    };
  • 相关阅读:
    Webpack实现按需打包Lodash的几种方法详解
    一文带你了解babel-preset-env
    Vue-给对象新增属性(使用Vue.$set())
    vue v-slot
    Vue2.4+新增属性.sync、$attrs、$listeners
    彻底搞定Javascript事件循环
    Spring Boot 添加JSP支持【转】
    防火墙设置
    黑黑客客
    tomcat启动时设定环境变量
  • 原文地址:https://www.cnblogs.com/fangkm/p/1486918.html
Copyright © 2020-2023  润新知