什么是堆放卷? [英] What is stack unwinding?

查看:162
本文介绍了什么是堆放卷?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是堆放?搜索过,但找不到启发答案!

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 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 ,即资源获取初始化 ,这有助于我们在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++.

现在,我们可以提供例外安全保证

Now that allows us provide exception safety guarantees.

这篇关于什么是堆放卷?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆