Why catch an exception as reference-to-const?(为什么要捕获异常作为对 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 的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么要捕获异常作为对 const 的引用?


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01