在C ++中抛出异常的生命周期 [英] Lifecycle of thrown exceptions in C++

查看:200
本文介绍了在C ++中抛出异常的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的简单C ++代码:

Consider the following simple C++ code:

void foo() {
    throw(my_exception());
}

void check_exc(const my_exception &exc) {
    /* Do stuff with exc */
}

void bar() {
    try {
        foo();
    } catch(const my_exception &exc) {
        check_exc(exc);
    }
}

bar 的异常处理程序, exc 引用的异常仍然存活,看到它是如何在 foo 的栈帧?应该不是那个框架在异常处理程序运行的时候被解开,并且分配的任何值已经被认为死了?特别是因为我显式调用另一个需要堆栈空间的函数。

In bar's exception handler, how comes the exception referenced by exc is still alive, seeing as how it was allocated in foo's stack frame? Shouldn't that frame have been unwound by the time the exception handler gets to run, and any values allocated there already be considered dead? Especially so since I'm explicitly calling another function which would need that stack space.

作为一个C程序员试图学习C ++,我在这里误解了什么?

As a C programmer trying to learn C++, what am I misunderstanding here? Where do these various values actually exist in memory, more precisely?

推荐答案

throw表达式中创建的临时变量用于初始化异常对象本身,(以引用标准)以未指定的方式分配。该对象持续(至少),直到异常被处理,所以处理程序对它的引用在处理程序或从处理程序调用的任何函数有效。

The temporary created in the throw-expression is used to initialise the exception object itself, which (to quote the standard) "is allocated in an unspecified way". That object lasts (at least) until the exception has been handled, so the handler's reference to it is valid within the handler, or any function called from the handler.

这篇关于在C ++中抛出异常的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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