Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Non-virtual destructor in base class

ID: cpp/virtual-destructorKind: problemSecurity severity: Severity: warningPrecision: highTags:   - reliability   - readability   - language-featuresQuery suites:   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

This rule finds classes with virtual functions but no virtual destructor. Deleting a class without a virtual destructor will only call the destructor of the type of the pointer being deleted. This can cause a defect if the pointer type is a base type while the object instance is a derived type.

Recommendation

Make sure that all classes with virtual functions also have a virtual destructor, especially if other classes derive from them.

Example

classBase{public:Resource*p;Base(){p=createResource();}virtualvoidf(){//has virtual function//...}//...~Base(){//wrong: is non-virtualfreeResource(p);}};classDerived:publicBase{public:Resource*dp;Derived(){dp=createResource2();}~Derived(){freeResource2(dp);}};intf(){Base*b=newDerived();//creates resources for both Base::p and Derived::dp//...//will only call Base::~Base(), leaking the resource dp.//Change both destructors to virtual to ensure they are both called.deleteb;}

References


[8]ページ先頭

©2009-2025 Movatter.jp