为什么要引用异常作为引用到const? [英] Why catch an exception as reference-to-const?

查看:145
本文介绍了为什么要引用异常作为引用到const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过并读过很多次,最好是引用一个异常作为引用到const,而不是引用。为什么是

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

优于

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


解决方案




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

  • 一个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).

这篇关于为什么要引用异常作为引用到const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆