Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Unsafe use of this in constructor

ID: cpp/unsafe-use-of-thisKind: path-problemSecurity severity: 7.5Severity: errorPrecision: very-highTags:   - correctness   - language-features   - security   - external/cwe/cwe-670Query suites:   - cpp-code-scanning.qls   - cpp-security-extended.qls   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

This rule finds calls to pure virtual member functions in constructors and destructors. When executing the body of a constructor of classT, the virtual table ofT refers to the virtual table of one ofT’s base classes. This can produce unexpected behavior, including program abort that can lead to denial of service attacks. The same problem exists during destruction of an object.

Recommendation

Do not rely on virtual dispatch in constructors and destructors. Instead, each class should be responsible for acquiring and releasing its resources. If a base class needs to refer to a derived class during initialization, use the Dynamic Binding During Initialization idiom.

Example

classBase{private:// pure virtual member function used for initialization of derived classes.virtualvoidconstruct()=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();}};classDerived:publicBase{intfield;voidconstruct()override{field=1;}};

References


[8]ページ先頭

©2009-2025 Movatter.jp