What is stack unwinding?(什么是堆栈展开?)
问题描述
什么是堆栈展开?搜索了一遍,但找不到有启发性的答案!
What is stack unwinding? Searched through but couldn't find enlightening answer!
推荐答案
堆栈展开通常与异常处理有关.这是一个例子:
Stack unwinding is usually talked about in connection with exception handling. Here's an example:
void func( int x )
{
char* pleak = new char[1024]; // might be lost => memory leak
std::string s( "hello world" ); // will be properly destructed
if ( x ) throw std::runtime_error( "boom" );
delete [] pleak; // will only get here if x == 0. if x!=0, throw exception
}
int main()
{
try
{
func( 10 );
}
catch ( const std::exception& e )
{
return 1;
}
return 0;
}
这里分配给pleak
的内存如果抛出异常会丢失,而分配给s
的内存会被std::string正确释放代码>析构函数在任何情况下.当退出范围时,分配在堆栈上的对象被展开"(这里的范围是函数
func
.)这是通过编译器插入对自动(堆栈)变量的析构函数的调用来完成的.
Here memory allocated for pleak
will be lost if an exception is thrown, while memory allocated to s
will be properly released by std::string
destructor in any case. The objects allocated on the stack are "unwound" when the scope is exited (here the scope is of the function func
.) This is done by the compiler inserting calls to destructors of automatic (stack) variables.
现在这是一个非常强大的概念,导致了称为 RAII 的技术,即 Resource Acquisition Is Initialization,帮助我们管理 C++ 中的内存、数据库连接、打开文件描述符等资源.
Now this is a very powerful concept leading to the technique called RAII, that is Resource Acquisition Is Initialization, that helps us manage resources like memory, database connections, open file descriptors, etc. in C++.
现在我们可以提供异常安全保证.
这篇关于什么是堆栈展开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是堆栈展开?


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01