問題描述
C++中異常對(duì)象的作用域是什么?一旦執(zhí)行 catch 處理程序,它是否會(huì)超出范圍?另外,如果我創(chuàng)建了一個(gè)未命名的異常對(duì)象并拋出它,那么在捕獲該異常時(shí),是通過常量引用還是非常量引用來捕獲它有關(guān)系嗎?
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?
推薦答案
當(dāng)對(duì) throw
表達(dá)式求值時(shí),會(huì)根據(jù)表達(dá)式的值初始化一個(gè)異常對(duì)象.拋出的異常對(duì)象從 throw 表達(dá)式的靜態(tài)類型獲取其類型,忽略任何 const
和 volatile
限定符.對(duì)于類類型,這意味著執(zhí)行復(fù)制初始化.
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.
異常對(duì)象的范圍在發(fā)生拋出的塊的范圍之外.可以把它想象成一個(gè)特殊的異常區(qū)域,遠(yuǎn)離本地對(duì)象所在的正常調(diào)用堆棧的一側(cè).
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
塊中,用捕獲的異常對(duì)象初始化的名稱是用這個(gè)異常對(duì)象初始化的,而不是 throw
的參數(shù),即使這是一個(gè)左值.
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
,那么你可以改變異常對(duì)象,但不能改變它的初始化對(duì)象.如果您以通過值或常量引用(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_cast
s aside).
當(dāng)最后一個(gè)沒有通過重新拋出(即無參數(shù)拋出表達(dá)式評(píng)估)退出的 catch 塊完成時(shí),異常對(duì)象被銷毀.
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.
這篇關(guān)于C++中異常對(duì)象的范圍的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!