1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>

 void b()
 { 
  throw std::exception();
 }
 
 void a()
 {
   std::string str = "Oops"; 
   b();
 }
 
 int main()
 {
   try
   {
      a();
   } 
   catch(...) 
   { }
 }

上面代码在堆栈展开过程中会发生以下情况:

1.main()调用a()。

2.a()创建一个名为str的局部变量。

3.str构造函数分配一个内存块来保存字符串“ Oops”

4.a()调用b()。

5.b()引发异常。

6.因为a()没有捕获到异常,所以我们现在需要以干净的方式退出a()。

7.在这一点上,所有在抛出之前的局部变量的析构函数都称为-这称为堆栈展开(stack unwinding)。

8.调用str的析构函数,它释放它所占用的内存。

9.堆栈展开机制对于防止资源泄漏至关重要-没有它,str将永远不会被破坏,并且它使用的内存将永远丢失。

10.main()捕获异常。

11.该程序继续。

https://www.bogotobogo.com/cplusplus/stackunwinding.php