Singleton模式笔记

本文介绍了C++中Singleton模式的两种实现方式,并讨论了如何避免单例对象带来的资源泄漏问题,包括使用atexit函数实现自动销毁及Meyers单例模式。

在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;
    }
};

转载于:https://www.cnblogs.com/fangkm/archive/2009/05/22/1486918.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值