问题描述
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 表达式的静态类型获取其类型,忽略任何 const 和 volatile 限定符.对于类类型,这意味着执行复制初始化.
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++中异常对象的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)