情况一:构造函数中有异常抛出
构造函数中有异常抛出,需要注意如果该构造函数中已在堆中生成了对象,要在构造函数中进行异常处理去释放堆中资源或者使用智能指针,因为这时构造函数未执行成功,对象还未创建成功,在栈回退时不会调用析构函数,进而造成内存泄漏;若在堆中生成的对象则无需担心,因为在栈回退时会释放。
测试代码如下:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"create A"<<endl;
}
~A()
{
cout<<"delete A"<<endl;
}
};
class Base
{
A * a;
public:
Base()
{
a=new A();
try
{
cout<<"create exception"<<endl;
throw 1;
}
catch(...)
{
delete a;
throw 1;
}
}
void fun() { throw 1; }
~Base() { delete a; }
};
int main()
{
try
{