問題描述
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_cast
s 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模板網!