当在一个函数中动态创建一个对象时如果在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的对象,从而达到目的.

275

被折叠的 条评论
为什么被折叠?



