在构造函数中不安全地使用 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
此规则查找在构造函数和析构函数中对纯虚成员函数的调用。执行类 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;
}
};
参考¶
ISO C++ 常见问题解答:当我的基类的构造函数在其 this 对象上调用虚函数时,为什么没有调用我的派生类对该虚函数的覆盖?
SEI CERT C++ 编码标准 OOP50-CPP。不要从构造函数或析构函数调用虚函数
ISO C++ 常见问题解答:好的,但是有没有办法模拟这种行为,就好像在我的基类的构造函数中,动态绑定对 this 对象有效一样?
常见弱点枚举:CWE-670。