本文介紹了為什么要捕獲異常作為對 const 的引用?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我多次聽說并閱讀過,最好將異常作為對常量的引用而不是作為引用來捕獲.為什么是:
I've heard and read many times that it is better to catch an exception as reference-to-const rather than as reference. Why is:
try {
// stuff
} catch (const std::exception& e) {
// stuff
}
優于:
try {
// stuff
} catch (std::exception& e) {
// stuff
}
推薦答案
您需要:
- 一個引用,以便您可以多態地訪問異常
- 用于提高性能的常量,并告訴編譯器您不會修改對象
后者不如前者重要,但放棄 const 的唯一真正原因是表明您想要對異常進行更改(通常只有在您想要更改時才有用)將添加的上下文重新拋出到更高級別).
The latter is not as much important as the former, but the only real reason to drop const would be to signal that you want to do changes to the exception (usually useful only if you want to rethrow it with added context into a higher level).
這篇關于為什么要捕獲異常作為對 const 的引用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!