如果在派生类中定义了虚拟析构函数,而不是层次结构的顶层定义了怎么办?C ++
问题描述:
我想知道定义没有虚拟析构函数的基类并定义具有虚拟析构函数的继承类是否正确?如果我这样做实际上会发生什么?
I wonder is it correct to define a base class with no virtual destructor, and define inherited classes with the virtual one? What would actually happen if I do that?
答
如果您删除p
,其中 p
的类型为 X *
,但是实际上指向从 X
派生的 Y
,除非 X
具有 virtual
析构函数,否则您具有未定义的行为.如果 Y
的析构函数是 virtual
,但是 X
的析构函数不是,则它完全不变.
If you delete p
where p
is of type X*
but actually points to a Y
which is derived from X
, you have undefined behavior unless X
has a virtual
destructor. If Y
's destructor is virtual
but X
s destructor is not it changes exactly nothing.