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

不应产生无效的临时对象

6.7.1 ID_inaccessibleTmpObject
目录 › next › previous

无名且不受控制的临时对象在构造之后会立即析构,往往意味着错误。

示例:

class A {
    int a;

public:
    A() {
        A(0);   // Non-compliant, just created an inaccessible temporary object
    }

    A(int x): a(x) {}
};

示例代码意在调用重载的构造函数,但 A(0); 只生成了一个无效的临时对象,成员并没有被正确初始化,应改用 this->A::A(0); 等形式,在遵循 C++11 标准的代码中也可将 A(0) 移入初始化列表:

class A {
    int a;

public:
    A(): A(0) {}        // Compliant, delegating constructor
    A(int x): a(x) {}
};

又如:

class LockGuard { .... };

void fun() {
    LockGuard();   // Non-compliant, meaningless
    ....
}

设 LockGuard 是某种 RAII 锁,LockGuard(); 只生成了一个临时对象,该对象会立即析构,起不到作用,这也是一种常见的错误。

应改为:

void fun() {
    LockGuard guard;   // Compliant
    ....
}

参考

CWE-665 C++ Core Guidelines ES.84
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.