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

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

问题描述


可能重复:

C ++中的指针捕获异常

我总是通过值捕获异常。例如

I always catch exceptions by value. e.g

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

但是我遇到了一些代码, code> catch(CustomException& e)。这是a)罚款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天全站免登陆