派生时的析构函数 class 包含指向基础 class 对象的指针

Destructor when derived class contains a pointer to base class object

我写了一个纯虚拟析构函数并在抽象基 class 中实现它并在派生 classes 中覆盖它。

但是,在其中一个 classes 中,我有一个指向基础 class 对象的指针。
现在,派生的 class 的析构函数应该这样写吗:

virtual ~DerivedClass()
{
delete this->pointerToAnotherDerivedClassObject;
}

或者对象会被自动删除?由于基本 class 析构函数总是被调用,所以我无法决定它是否处理它。

编辑: 我错误地指出它是指向基础 class 的指针,因为它实际上是另一个派生 class 对象的指针。

However, in one of the classes I have a pointer to a base class object. Now, should the destructor of the derived class be written this way

因为 pointerToAnotherDerivedClassObject 指向内存中的 另一个 对象,那么是的,你的 DerivedClass 析构函数需要显式 delete 该对象(或将原始指针包装在智能指针中 - std::auto_ptrstd::unique_ptrstd::shared_ptr - 并让它 delete 对象) ONLY IF DerivedClass 意味着拥有另一个对象。否则,如果您不拥有它,请不要 delete 它。

@Elia 在设计模式第 10 章中关于伪虚拟构造函数的 Eckel 的“Thinking in C++ vol-2”一书中讨论了类似的情况。考虑到您动态分配它,您的问题的答案是您确实需要删除它。也不要将成员 Base* 与由于继承而派生的 Base 对象混淆,一个是数据成员(这是您要删除的),另一个是由于继承。