1 try块中已生成的对象会被自动回收
new出来的不会自动回收 需要使用auto_ptr<T> p指针。
2 构造函数中若抛出异常,这个未构造好的对象不会被回收。 也要使用auto_ptr来设定好。
#include <iostream>
#include <memory>
using namespace std;
class A{
public:
A(){cout<<"A()"<<this<<endl;}
~A(){cout<<"~A()"<<this<<endl;}
};
class B{
public:
B(){cout<<"B()"<<this<<endl;}
~B(){cout<<"~B()"<<this<<endl;}
};
class D{
public:
D(){cout<<"D()"<<this<<endl;}
~D(){cout<<"~D()"<<this<<endl;}
};
class C
{
auto_ptr<D> p;
public:
C(int n)
{
auto_ptr<D> q(new D);
q = p;
if(n < 0) throw 888;
}
~C()
{
}
};
int main()
{
try{
auto_ptr<A> p(new A); //抛出异常前自动释放
B* q(new B); //q只是个指针 需要手动释放 这里需要auto_ptr
B b; // 在try块内的对象在抛出异常前 会先自动释放
C oc(-3); //这里的异常发生在构造函数中,虽然是对象,但不会自动释放,构造函数中若有手动创建的
//构造中分配的堆空间也要auto_ptr
int n;
cin >> n;
if(n<0)
throw 123;
cout << "n=" << n << endl;
delete q;
}
catch(int e){
cout << "exception: " << e << endl;
}
}