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

标签 c++

通过指向基类的指针删除派生类实例的常见做法是在基类中声明虚拟析构函数。但我很好奇如果派生类没有向基类添加新成员并且基类的析构函数是非虚拟的,会发生什么。

想象一下下面的设计。基类有一个 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/

相关文章:

c++ - 360 游戏 Controller Linux 设备驱动程序问题调用我的探测功能

c++ - io.h 中的 _write 是阻塞调用吗?

c++ - 使用 (MFC) CList<T, T&> 而不是 CList<T, const T&> 的任何理由?

c++ - QObject::connection(const QObject*, const char*, const char*, Qt::ConnectionType) "Cannot convert argument 3 from ' fileProcessor' to const QObject *"

java - 如何实现良好的客户端-服务器方法?

c++ - 在不损失性能的情况下提高代码可读性

C++:在构造函数>中进行完整性检查时,我是否需要/可以使用异常处理?

c++ - 不能使用 `deflateInit`压缩修改后的数据

c++ - 如果存在依赖关系,编译器能否正确处理静态变量的初始化顺序?

c++ - 在 C++ 中存储和检索复杂对象的有效方法?