如果在派生类中定义了虚拟析构函数,而不是层次结构的顶层定义了怎么办?C ++ [英] What if the virtual destructor defined in derived class, but not the top of hierarchy? C++

查看:40
本文介绍了如果在派生类中定义了虚拟析构函数,而不是层次结构的顶层定义了怎么办?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 Xs destructor is not it changes exactly nothing.

这篇关于如果在派生类中定义了虚拟析构函数,而不是层次结构的顶层定义了怎么办?C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆