异常安全-对象生命周期

对象生命周期:构造函数调用结束后,析构函数调用之前。

类的非托管成员变量(自己new出来的对象、数组等等),永远不要写到初始化列表中

例:
class InilException 
{
public:
 InilException();
 virtual ~InilException();
public:
 int* m_array;
};

类InilException中含有非托管的成员变量 m_array;

构造函数
InilException::InilException()
:m_array(new int[10])
{

}
InilException::~InilException()
{
 delete [] m_array;
}

上述是一个错误写法。

如果InilException在构造函数中抛出了异常,那么没有机会释放m_array。原因是构造函数并未执行结束,对象没有真实存在,自然不会调用到析构函数。

由于VC6不支持Function try block。所以也无法对初始化列表加以异常捕捉。

例如

class Unlucky
{
public:
 Unlucky()
 {
  throw 1;
 }
};
class InilException 
{
public:
 InilException();
 virtual ~InilException();
public:
 int* m_array;
 Unlucky m_u;
};

 

InilException::InilException()
:m_array(new int[10]),
m_u()
{

}

InilException::~InilException()
{
 delete [] m_array;
}

会产生内存泄漏。

正确方法

1 使用智能指针。

2

InilException::InilException()
:m_array(NULL),
m_u()
{

try

{

    m_array = new int[10] 

}

catch(...)

{

    delete m_arrray;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值