通过指向基类的指针删除派生类实例的常见做法是在基类中声明虚拟析构函数。但我很好奇如果派生类没有向基类添加新成员并且基类的析构函数是非虚拟的,会发生什么。
想象一下下面的设计。基类有一个 protected 构造函数,因此不能直接创建它。这里派生类的唯一目的是允许某些工厂类创建基类。工厂实例化派生类并返回指向基类的指针。最终,当用户删除指向的实例时,当然不会调用派生类的析构函数,但我不确定是否有必要,因为派生类没有添加新数据。我想弄清楚在这种情况下可能出现什么样的问题(如果有的话)。
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.
无论派生类的成员如何,程序的行为都将是未定义的。
关于c++ - 通过指向基类的指针删除没有新成员的派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60831103/