本文主要讨论为什么析构函数不建议抛出异常!!!
class base{
public:
base(){
x = 1;
y = 2;
cout << "the object has constructed!"<< endl;
}
~base(){
cout << "destructor has excuted!"<< endl;
}
int x ;
int y;
};
int print(int x){
cout << x << endl;
throw 1;
cout << "after a exception!"<< endl;
return 0;
}
int widget(int a, int b){
base cc;
print(a);
return 0;
}
int bar(int a, int b){
base bb;
int c = widget(a, b);
return 0;
}
int foo(int a, int b){
int c=1;
try{
c = bar(a, b);
}
catch(int x){
cout << x << endl;
cout << "the exception has caught!"<< endl;
}
cout << "after caugth!"<< endl;
return c;
}
int main(){
int re=foo(1, 2);
cout << "re:"<<re << endl;
return 0;
}
输出:
这种情况下,析构函数并没有抛出异常,程序可以继续执行!!!
但是当我们修改语句之后:
class base{
public:
base(){
x = 1;
y = 2;
cout << "the object has constructed!"<< endl;
}
~base(){
try{
throw 3;
}
catch(int y){
cout << "exception has been solved insie!"<< endl;
}
cout << "destructor has excuted!"<< endl;
}
int x ;
int y;
};
这种情况下,被抛出的异常可以在当前函数的栈范围解决,就不会栈展开!!!
再修改:
class base{
public:
base(){
x = 1;
y = 2;
cout << "the object has constructed!"<< endl;
}
~base(){
cout << "destructor has excuted!"<< endl;
throw 3;
}
int x ;
int y;
};
输出:
可以看出,编译器调用terminate执行abort()终止进程!!!!为什么会这样?下面是我的理解:
当我们调用print函数的时候,函数抛出一个异常,但是这个异常在函数内部又不能被解决,所以这个异常被继续抛出,那么此时从FS:[0](个人理解FS:[0]代表在异常被抛
出后,catch块对应的异常处理就从FS:[0]指向的SHL开始向上寻找,直到找到对应的catch块)开始向上遍历 SHL 节点,匹配到catch 块,一旦找到就展开从FS:[0]到foo之间
的栈空间(unwind stack).在此期间会析构已建立的对象。当析构widget中的base cc对象时,析构函数又抛出异常,但是这个异常不能被内部解决,就会被抛出道函数外部,
那么FS:[0]就会指向widget栈中的SHL结点,从该节点网上寻找到foo异常处理语句,那么在widget栈和foo栈之间的对象又要被释放,又要调用析构函数,如此一来,就会陷入
无限的递归嵌套之中!!!!