C ++中异常对象的范围 [英] Scope of exception object in C++

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

问题描述

C ++中的异常对象的范围是什么?一旦catch处理程序被执行,它是否超出范围?此外,如果我创建一个未命名的异常对象并抛出它,然后捕获该异常,它是否重要,如果我捕获它的const引用或非const引用?

解决方案

评估 throw 表达式时,会初始化异常对象从表达式的值。抛出的异常对象从throw表达式的静态类型中获取其类型,忽略任何 const volatile 限定符。对于类类型,这意味着将执行复制初始化



异常对象的作用域超出了发生抛出的块的范围。



在一个 catch

里面, code> block,用捕获的异常对象初始化的名称用这个异常对象初始化,而不是 throw 的参数,即使这是一个左值。 p>

如果你 catch 通过非const引用,那么你可以改变异常对象,而不是它被初始化。如果你通过值或const引用( const_cast s aside)捕获的方式重新抛出异常,你可以改变程序的行为。 / p>

当最后一个没有通过re throw抛出的catch块(即无参数的throw表达式求值)完成时,异常对象被销毁。


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?

解决方案

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.

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.

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).

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 ++中异常对象的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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