☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

重新抛出异常时应使用空 throw 表达式(throw;)

7.22 ID_improperRethrow
目录 › next › previous

重新抛出异常时应使用空 throw 表达式,避免异常对象的精度损失和不必要的复制开销。

示例:

class Base {};
class Derive: public Base {};

void foo() {
    try {
        throw Derive();
    }
    catch (Base& e) {
        throw e;        // Non-compliant, use ‘throw;’ instead
    }
}

void bar() {
    try {
        foo();
    }
    catch (Derive& e) {   // Cannot catch Derive
        ....
    }
}

注意,例中 foo 函数虽然捕获的是 Derive 对象,但 throw e; 抛出的是 Base 对象,这也是一种“对象切片”问题,造成了对象类型的“精度损失”。将 throw e; 改为 throw; 可解决这种问题。

依据

ISO/IEC 14882:2003 15.1(6) ISO/IEC 14882:2011 15.1(8)
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.