gpt4 book ai didi

c++ - 不用于删除对象的基类的析构函数应该是虚拟的吗?

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:17 24 4
gpt4 key购买 nike

假设我有两个基类,

struct A {}; 
struct B {};

和派生的使用多重继承

struct D : A, B {}; 

如果我的使用场景是这样的:

A *obj = new D; 

即我永远不会使用 B 基类来引用派生对象,我是否必须将两个基类的析构函数都设为虚拟?我目前正在将 B 的析构函数声明为 protected 以禁止其他用户这样做,但这是否足够?

D 的析构函数呢?

最佳答案

B 的析构函数不必是虚拟的,只要 B* 从未用于删除派生对象。参见 [expr.delete]/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.

在这种情况下,“静态类型”是 T cv 类型,其中 delete 的操作数具有类型 T 简历 *。因此,您的案例中的要求强加于 A,而不是 B

关于c++ - 不用于删除对象的基类的析构函数应该是虚拟的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41709089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com