2

Sutter 和 Alexandrescu 的编码标准告诉我们通过引用来捕获异常。

当然,像这样的一揽子建议通常偶尔会有例外(没有双关语)。是否存在应该首选按值捕获异常的用例?

4

1 回答 1

5

The advantage to catching a reference, besides obvious reasons of not requiring copyability or performing a copy (potentially a slicing one), is that you can modify it and continue processing with throw;.

If you want to modify the object, yet continue exception processing with throw; on the non-modified object, then you must make a copy, and one way of doing so is catch by value.

I think it's pretty contrived, though. Catch by const reference followed by an explicit copy would better express intent.

Also note, throwing a new C++11 nested_exception will nest the previously thrown exception object, not the object received by value, within the new exception. In such conditions you could conceivably keep your own reference to the received exception, which would go stale unless you received it by reference.

于 2013-07-18T02:49:22.033 回答