c++ - 执行 "delete this"时缺少虚拟析构函数

标签 c++ polymorphism virtual-destructor self-destruction

16.15 of the C++ FAQ Lite讨论 delete this 然后提到:

Naturally the usual caveats apply in cases where your this pointer is a pointer to a base class when you don't have a virtual destructor.

为什么是这样?考虑这段代码:

class ISuicidal {
public:
    virtual void suicide() = 0;
};

class MyKlass : public ISuicidal {
public:
    MyKlass() {
        cerr << "MyKlass constructor\n";
    }

    ~MyKlass() {
        cerr << "MyKlass destructor\n";
    }

    void suicide() {
        delete this;
    }
};

这样使用:

int main()
{
    ISuicidal* p = new MyKlass;
    p->suicide();
    return 0;
}

在调用 p->suicide() 时,MyKlass 的析构函数按预期被调用,即使 ISuicidal 具有没有虚拟析构函数

对我来说这是有道理的,因为在 MyKlass::suicide 中,this 的静态类型已知为 MyKlass*,所以正确的析构函数被调用。这很容易通过将 typeid 调用放在 suicide 中来验证。

那么是FAQ条目不准确,还是我误解了?

最佳答案

你误会了。在ISuicidal中实现自杀函数(即delete this),你会发现当this指针是基类时调用delete并不会调用派生类的析构函数。

关于c++ - 执行 "delete this"时缺少虚拟析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7440727/

相关文章:

c++ - 是否计划为 future 的 C++ 版本修订 std::allocator 接口(interface)?

c++ - 在 C++ 中将字节字符串拆分为 BYTES vector

c++ - 如何解决 "pure virtual method called"

c++ - 构造函数和析构函数中的虚函数调用

c++ - 如何使用 glPolygonStipple 创建粗斜条纹?

c++ - linux 发送带有标志 MSG_DONTWAIT 的调用

python - Flask 基于类的 View ——多态性

Java:从扩展子类获取对象的最佳方法

c++ - "The Rule of Zero"是否也适用于具有虚方法的类?

c++ - 纯抽象类的虚拟析构函数