且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么要引用异常作为引用到const?

更新时间:2023-11-11 23:32:28




  • 一个引用,所以你可以多次访问该异常

  • 一个const来提高性能,不会修改对象



后者不像以前那样重要,但是只有真正的原因,降低const将是信号,你想做的更改异常(通常只有当你想重新抛出它与添加上下文到更高的级别)。


I've heard and read many times that's better to catch an exception as reference-to-const rather than as reference. Why is

try {
    // stuff
} catch (const std::exception& e) {
    // stuff
}

better than

try {
    // stuff
} catch (std::exception& e) {
    // stuff
}

You need:

  • a reference so you can access the exception polymorphically
  • a const to increase performance, and tell the compiler you're not going to modify the object

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).