gpt4 book ai didi

没有虚拟析构函数的 C++ 继承

转载 作者:搜寻专家 更新时间:2023-10-31 00:15:27 25 4
gpt4 key购买 nike

如果父类的析构函数不是虚函数,但是子类没有额外的成员,那么使用父类的析构函数安全吗?

class A{
~A();
protected:
int i;
};
class B: public A{

}

A *x = new B; delete x;

最佳答案

这不安全,根据 §5.3.5,这是未定义的行为

5.3.5 Delete [expr.delete]

3 In the first alternative (delete object), 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. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

为什么它可能会崩溃的一个例子是:

class A
{
public:
~A();
protected:
int i;
};

class B: public A
{
virtual void dummy();
}

A *x = new B; delete x;

现在 B 有一个 vtbl,因此对象布局不同。

顺便说一句:public class A 是 Java 或其他语言,但不是 C++。

关于没有虚拟析构函数的 C++ 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19339938/

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