如何在堆栈上分配的异常超出了它们的范围? [英] How are exceptions allocated on the stack caught beyond their scope?

查看:126
本文介绍了如何在堆栈上分配的异常超出了它们的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,基于堆栈的变量'ex'被抛出并捕获在超出声明范围的函数中。这看起来有点奇怪,因为(AFAIK)基于堆栈的变量不能在它们被声明的范围之外使用(堆栈解开)。

In the following code, the stack-based variable 'ex' is thrown and caught in a function beyond the scope in which ex was declared. This seems a bit strange to me, since (AFAIK) stack-based variables cannot be used outside the scope in which they were declared (the stack is unwound).

void f() {
    SomeKindOfException ex(...);
    throw ex;
}

void g() {
    try {
        f();
    } catch (SomeKindOfException& ex) {
        //Handling code...
    }
}

我向SomeKindOfException的析构函数添加了一个打印语句,并且它显示ex一旦在f()中超出范围就被析构,然后它被g()捕获并再次被破坏一旦它离开范围,以及。

I've added a print statement to SomeKindOfException's destructor and it shows that ex is destructed once it goes out of scope in f() but then it's caught in g() and destructed again once it goes out of scope there as well.

任何帮助?

推荐答案

异常对象被复制到特殊的位置生存堆栈展开。你看到两个破坏的原因是因为当你退出f()原始异常被销毁,当你退出g()复制被销毁。

The exception object is copied to a special location to survive the stack unwinding. The reason you see two destructions is because when you exit f() the original exception is destroyed and when you exit g() the copy is destroyed.

这篇关于如何在堆栈上分配的异常超出了它们的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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