C ++ catch块 - 通过值或引用捕获异常? [英] C++ catch blocks - catch exception by value or reference?

查看:153
本文介绍了C ++ catch块 - 通过值或引用捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

捕获异常通过指针在C ++

通过值捕获异常。

try{
...
}
catch(CustomException e){
...
}

但是我遇到了一些代码, code> catch(CustomException& e)。这是一个很好的b)错误c)一个灰色区域?

But I came across some code that instead had catch(CustomException &e) instead. Is this a)fine b)wrong c)a grey area?

推荐答案

C ++中的异常的标准做法是...

The standard practice for exceptions in C++ is ...


按值引用

Throw by value, catch by reference

按照值进行捕捉在面对继承层次结构时是有问题的。假设您的示例中有另一个类型 MyException ,它继承自 CustomException 并覆盖像错误代码等项。如果一个 MyException 类型被抛出,您的catch块将导致它被转换为一个 CustomException 实例,代码改变。

Catching by value is problematic in the face of inheritance hierarchies. Suppose for your example that there is another type MyException which inherits from CustomException and overrides items like an error code. If a MyException type was thrown your catch block would cause it to be converted to a CustomException instance which would cause the error code to change.

参考资料

  • http://www.oreillynet.com/pub/a/network/2003/05/05/cpluspocketref.html

这篇关于C ++ catch块 - 通过值或引用捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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