Ale*_*Dan 2 c++ exception-handling exception
代码:
#include<iostream>
using namespace std;
class A{
public:
A(){cout << "A() Constructor " << endl;
throw 1;
}
};
int main(){
A* p=0;
cout << p << endl; // p value is 0
try{
p=new A(); // object is not fully constructed, no address is returned to p. for future deallocation
}
catch(...){cout << "Exception" << endl;}
cout << p << endl; // this will output that p has the value 0,proof that no address was returned to p.
}
Run Code Online (Sandbox Code Playgroud)
内存是为堆中的A对象分配的,内存的地址是传递给构造函数的,但是当构造函数throw 1;然后类型的对象A不被认为是完全构造的对象时.所以没有指针将返回指针p.如果我理解错误,请随时纠正我.
问题:
1)所以我的问题是在这种情况下如何为A对象释放内存.我不是在谈论析构函数调用,而是释放内存.
2)当我A在main函数内部创建类型的本地对象时怎么样?显然它也不会完全构建.何时释放此对象(在调用完全构建的子对象的析构函数之后).
完成的分配由new A()多个步骤组成:
operator new(sizeof(A))。operator delete(x)使用之前获得的地址进行调用。更一般地,如果您使用重载的operator new(),例如,new(allocator) A()which 调用operator new(size_t, Alloctor)(其中allocator可转换为),则会调用Allocator相应的。operator delete()
作为异常抛出的一部分,所有部分构造的子对象也会被销毁(以与构造它们的顺序相反的顺序)。也就是说,如果对象的构造函数抛出异常,您不需要关心清理(假设所有子对象都正确地处理它们分配的资源)。无论对象是在堆上还是在堆栈上分配,这都是正确的。
| 归档时间: |
|
| 查看次数: |
700 次 |
| 最近记录: |