避免动态分配内存后因异常而导致的内存泄露

 当在一个函数中动态创建一个对象时如果在delete之前发生异常就会导致内存泄露,原因很简单,因为程序没有处理delete,如果是局部变量,则会保证局部变量的释放.所以我们需要定义一个类来管理NEW来的内存通过在函数中定义局部对象,在异常发生的时候就会自动释放.也就是说自动调用他的析构函数.我们可以在它的构造函数中去NEW一个我们要得对象,而类中保留一个数据成员存放NEW返回的指针,析构时DELETE指针就好了.

 

#include  " iostream "
using  std::endl;
using  std::cout;
using  std::cin;
using  std::bad_alloc;
using  std::ostream;

class  fushu {
public:
    fushu(
int x,int y);
    friend ostream
& operator<<(ostream& out,const fushu& linshi);
    fushu 
operator+(fushu& anotherfu);    
    
~fushu()
    
{
        cout
<<"fushu destroy!"<<endl;
    }

    
int a;
    
int b;
}
;

fushu fushu::
operator + (fushu &  anotherfu)
{
    fushu c(
0,0);
    
if (a==anotherfu.a && b==anotherfu.b) {
        
throw (anotherfu);
    }

    c.a
=a+anotherfu.a;
    c.b
=b+anotherfu.b;
    
return c;
}

fushu::fushu(
int  x, int  y): a(x),b(y)
    
{
        cout
<<"fushu constrct!"<<endl;
    }


ostream
&   operator << (ostream &   out , const  fushu &  linshi)
{
    
out<<linshi.a<<" "<<linshi.b<<endl;
    
return out;
}


class  auto_p {
public:
    auto_p(fushu
& m);
    auto_p(fushu
* mm);
    
~auto_p();

    fushu
* p;
}
;

auto_p::auto_p(fushu 
& m)
{
    p
=new fushu(m);
    cout
<<"auto_p construct!"<<endl;
}


auto_p::auto_p(fushu
*  mm)

    p
=mm;
    cout
<<"auto_p construct with fushu *"<<endl;
}


auto_p::
~ auto_p()
{
    delete p;
    cout
<<"auto_p destroy!"<<endl;
}


void  fun()
{
    fushu fu(
10,20);
    auto_p mauto(fu);
    auto_p mautoptr(
new fushu(10,20));
    cout
<<(*mautoptr.p+*mauto.p)<<endl;
}


int  main()
{
    
try{
        fun();
       }

    
catch (fushu & aaa) {
      cout
<<aaa.a<<"and"<<aaa.b<<"same to fushu with mauto point to!"<<endl;
    }

    
return 0;
}

 

这样当异常发生时,会自动调用AUTO_P的析构函数,因为对象是局部的,而析构函数又会DELETE FUSHU的对象,从而达到目的.

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值