简体   繁体   English

通过指向基类的指针删除没有新成员的派生类

[英]Deletion of a derived class without new members through a pointer to the base class

A common practice for deleting a derived class instance through a pointer to its base class is declaring a virtual destructor in the base class.通过指向其基类的指针删除派生类实例的常见做法是在基类中声明一个虚拟析构函数。 But I am curious what happens in case the derived class adds no new members to the base class and the base class' destructor is non-virtual.但是我很好奇如果派生类没有向基类添加新成员并且基类的析构函数是非虚拟的,会发生什么。

Imagine, the following design.想象一下,下面的设计。 The base class has a protected constructor, so it can't be created directly.基类有一个受保护的构造函数,所以不能直接创建。 The only purpose of the derived class here is to allow base class creation by some Factory class.这里派生类的唯一目的是允许某些工厂类创建基类。 The Factory instantiates the derived class and returns a pointer to the base class.工厂实例化派生类并返回指向基类的指针。 Eventually, when the pointed instance gets deleted by a user, the destructor of the derived class won't be called, of course, but I'm not sure if it's necessary since the derived class adds no new data.最终,当指向的实例被用户删除时,派生类的析构函数当然不会被调用,但我不确定是否有必要,因为派生类没有添加新数据。 I'd like to clear up what kind of problems (if any) are possible in this case.我想弄清楚在这种情况下可能出现什么样的问题(如果有的话)。

class Base
{
public:
    ~Base() = default;

protected:
    Base(int x, int y): x(x), y(y) {}

private:
    int x, y;
};

class Factory
{
    // privately declared Derived class exposes protected constructor from the Base class
    class Derived : public Base
    {
    public:
        Derived(int x, int y) : Base(x, y) {}
        ~Derived() = default;
    };

public:

    Base* create(int x, int y)
    {
        return new Derived(x, y);
    }
};  // Factory


int main()
{
    Factory factory;
    Base *base = factory.create(3, 4);
    delete base;
}

But I am curious what happens in case the derived class adds no new members to the base class and the base class' destructor is non-virtual.但是我很好奇如果派生类没有向基类添加新成员并且基类的析构函数是非虚拟的,会发生什么。

The behaviour of the program will be undefined regardless of the members of the derived class.无论派生类的成员如何,程序的行为都将是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM