基类中的非虚析构函数¶
ID: cpp/virtual-destructor
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- reliability
- readability
- language-features
Query suites:
- cpp-security-and-quality.qls
此规则查找具有虚函数但没有虚析构函数的类。删除没有虚析构函数的类只会调用被删除指针类型的析构函数。如果指针类型是基类型,而对象实例是派生类型,则这会导致缺陷。
建议¶
确保所有具有虚函数的类也具有虚析构函数,特别是如果其他类派生自它们。
示例¶
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;
}
参考¶
S. Meyers. Effective C++ 3d ed. pp 40-44. Addison-Wesley Professional, 2005.