为什么要捕获异常作为对 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).
相关文章