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

标签 c++ inheritance

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

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/

相关文章:

c++ - ZeroMQ的REQ-REP模式如何获取请求者的公网IP?

c# - base() 和 this() 构造函数最佳实践

c++ - Direct3d 和 glsl 不同大小的顶点和多维几何对象?

c++ - 自定义迭代器和自定义常量迭代器之间的转换

c++ - 3D vector 索引不一致 C++

c++ - 继承一个带有内部类的模板类,并在继承类中访问内部类

基于模板的派生类和可变参数的 C++ 构造函数

java - 如何在 Android 中的 Activity 之间访问相同的变量

c# - 如何在不使用反射的情况下访问一系列类的公共(public)属性

c++ - 未定义错误构造函数