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

不应存在没有被用到的局部声明

6.12.7 ID_invalidLocalDeclaration
目录 › next › previous

没有被用到的局部声明是没有意义的,往往意味着代码冗余或功能不完整,也可能导致严重的逻辑错误。

示例:

int foo(int n) {
    int x = 0;
    if (n) {
        int x = 100 / n;   // Non-compliant
    }
    return x;
}

在 if 作用域中声明的 x 对象没有被使用,与其相关的计算过程是无效的。

应改为:

int foo(int n) {
    int x = 0;
    if (n) {
        x = 100 / n;   // Compliant
    }
    return x;
}

具有特定构造或析构函数的 C++ 对象可以做到“声明即使用”,但要注意如下情况:

struct LockGuard {
    LockGuard();
   ~LockGuard();
};

void bar() {
    LockGuard guard();   // Non-compliant, this is a function
    do_something();
}

例中 guard 意在实现某种 RAII 锁,但 LockGuard guard(); 是函数而不是对象,构造和析构函数不会按预期执行,这也是一种常见笔误。

应改为:

void bar() {
    LockGuard guard;   // Compliant
    do_something();
}

在某些特殊情况下,如断言中的变量在发布版本中没有被用到:

void test(int a, int b) {
    [[maybe_unused]] bool x = a > b;  // C++17 attribute,
                                      // or use __attribute__((unused)) in GCC,
    assert(x);                        // assert is compiled out in release mode
}

例中变量 x 在定义了 NDEBUG 的版本中没有被用到,并使用 [[maybe_unused]] 属性声明,这种情况可不受本规则限制。

依据

ISO/IEC 14882:2017 10.6.6

参考

MISRA C++ 2008 0-1-3
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.