CodeQL 文档

在构造函数中不安全地使用 this

ID: cpp/unsafe-use-of-this
Kind: path-problem
Security severity: 7.5
Severity: error
Precision: very-high
Tags:
   - correctness
   - language-features
   - security
   - external/cwe/cwe-670
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

单击以在 CodeQL 代码库中查看查询

此规则查找在构造函数和析构函数中对纯虚成员函数的调用。执行类 T 的构造函数体时,T 的虚表指的是 T 的某个基类的虚表。这可能会产生意外行为,包括可能导致拒绝服务攻击的程序中止。在销毁对象期间也存在相同的问题。

建议

不要依赖构造函数和析构函数中的虚函数调度。相反,每个类都应该负责获取和释放其资源。如果基类在初始化期间需要引用派生类,请使用初始化期间的动态绑定惯用法。

示例

class Base {
private:
    // pure virtual member function used for initialization of derived classes.
    virtual void construct() = 0;
public:
    Base() {
        // wrong: the virtual table of `Derived` has not been initialized yet. So this
        // call will resolve to `Base::construct`, which cannot be called as it is a pure
        // virtual function.
        construct();
    }
};

class Derived : public Base {
    int field;

    void construct() override {
        field = 1;
    }
};

参考

  • ©GitHub 公司
  • 条款
  • 隐私