C++中异常对象的范围

Scope of exception object in C++(C++中异常对象的范围)

本文介绍了C++中异常对象的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++中异常对象的作用域是什么?一旦执行 catch 处理程序,它是否会超出范围?另外,如果我创建了一个未命名的异常对象并抛出它,那么在捕获该异常时,是通过常量引用还是非常量引用来捕获它有关系吗?

What is the scope of the exception object in C++? does it go out of scope as soon as catch handler is executed? Also, if I create an unnamed exception object and throw it, then while catching that exception does it matter if I catch it by const reference or a non-const reference?

推荐答案

当对 throw 表达式求值时,会根据表达式的值初始化一个异常对象.抛出的异常对象从 throw 表达式的静态类型获取其类型,忽略任何 constvolatile 限定符.对于类类型,这意味着执行复制初始化.

When a throw expression is evaluated, an exception object is initialized from the value of the expression. The exception object which is thrown gets its type from the static type of the throw expression ignoring any const and volatile qualifiers. For class types this means that copy-initialization is performed.

异常对象的范围在发生抛出的块的范围之外.可以把它想象成一个特殊的异常区域,远离本地对象所在的正常调用堆栈的一侧.

The exception object's scope is outside of the scope of the block where the throw occurs. Think of it as living in a special exception area off to one side of the normal call stack where local objects live.

catch 块中,用捕获的异常对象初始化的名称是用这个异常对象初始化的,而不是 throw 的参数,即使这是一个左值.

Inside a catch block, the name initialized with the caught exception object is initialized with this exception object and not the argument to throw, even if this was an lvalue.

如果你通过非常量引用catch,那么你可以改变异常对象,但不能改变它的初始化对象.如果您以通过值或常量引用(const_cast 暂且不提)捕获的方式重新抛出异常,您可以改变程序的行为.

If you catch via non-const reference, then you can mutate the exception object, but not what it was initialized from. You can alter the behaviour of the program if you re-throw the exception in ways that you couldn't if you caught by value or const reference (const_casts aside).

当最后一个没有通过重新抛出(即无参数抛出表达式评估)退出的 catch 块完成时,异常对象被销毁.

The exception object is destroyed when the last catch block that does not exit via a re-throw (i.e. a parameterless throw expression evaluation) completes.

这篇关于C++中异常对象的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++中异常对象的范围

基础教程推荐