为什么基类的析构函数是虚函数? [英] Why should the destructor of base classes be virtual?
问题描述
在C ++中:为什么基类的析构函数是虚拟的?
为什么。你的问题表明你认为所有的基类应该有虚拟析构函数,这是不真实的。
这将使得不可能应用空基类优化,并且可以将类的大小乘以16倍,而不是
DerivedClass
的对象类型为 BaseClass *
。 virtual
使编译器在对象中关联信息,使其能够执行派生类析构函数。在这种情况下缺少 virtual
会导致未定义的行为。 如果你不需要这个,你的类只用作基类,最好让析构函数 protected
,从而防止用户以上述方式意外地删除
。
in C++: Why should the destructor of base classes be virtual?
The better question is when and why. Your question indicates that you think all base classes should have virtual destructors, which is not quite true.
It would make it impossible to apply the empty base class optimization, and could multiply the size of classes up to 16 times than what it would be without virtual
on common platforms.
A virtual
destructor is needed when you delete
an object whose dynamic type is DerivedClass
by a pointer that has type BaseClass*
. The virtual
makes the compiler associate information in the object making it able to execute the derived class destructor. Missing the virtual
in such case causes undefined behavior.
If you don't need this, and your class is only used as a base class, it's best to make the destructor protected
, thus preventing that users accidentally delete
in the described way.
这篇关于为什么基类的析构函数是虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!