0%

栈展开:C++自带功能

2020年3月16日 下午5:11

补充:2020年5月20日 下午7:26

  1. 所谓的异常catch其实就是一个函数调用

定义:

编译器会自动调用析构函数,包括在函数执行发生异常的情况。在发生异常时对析构函数的调用,还有一个专门的术语,叫栈展开(stack unwinding)

实例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>

class Obj {
public:
Obj() { puts("Obj()"); }
~Obj() { puts("~Obj()"); }
};

void foo(int n)
{
Obj obj;
if (n == 42)
throw "life, the universe and everything";
}

int main()
{
try {
foo(41);
foo(42);
}
catch (const char* s) {//从这里就可以看出来,所谓的异常catch其实就是一个函数调用
puts(s);
}
}

执行代码的结果是:

1
2
3
4
5
Obj()
~Obj()
Obj()
~Obj()
life, the universe and everything

也就是说,不管是否发生了异常,obj 的析构函数都会得到执行。