CodeQL documentation

Non-virtual destructor in base class

ID: cpp/virtual-destructor
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - reliability
   - readability
   - language-features
Query 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

class Base {
public:
	Resource *p;
	Base() {
		p = createResource();
	}
	virtual void f() { //has virtual function
		//...
	}
	//...
	~Base() { //wrong: is non-virtual
		freeResource(p);
	}
};

class Derived: public Base {
public:
	Resource *dp;
	Derived() {
		dp = createResource2();
	}
	~Derived() {
		freeResource2(dp);
	}
};

int f() {
	Base *b = new Derived(); //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.
	delete b;
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy