Do I need a virtual destructor if descendant classes have no non-static members or destructors?
我在玩弄文件描述符的类层次结构,其中基类持有一个int并在销毁期间对其调用
如果您打算使用基类指针通过
1 2 3 4 5 6 7 8 | class Foo {}; class Bar : public Foo {} int main() { Foo* f = new Bar; delete f; // << UNDEFINED BEHAVIOR without virtual destructor in base classe } |
如果您需要对象具有多态性,那么您还需要在基中至少有1个
如果通过指向基类的指针来
C++ 11标准,第5.3.5/3页:
If the static type of the object to be deleted is different from its
dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.
但是,如果类的构造函数不同,可以考虑使用派生的替代方法,例如简单的自由函数,如