c++ 纯虚基类指针 delete 时未调用 non-virtual destructor

#include <iostream>

using namespace std;

class Base
{
public:
    ~Base() // 注意,这不是 virtual
    {
        cout << "~base\n";
    }

    virtual void func() = 0;

};


class BasePlus: public Base
{
public:
    ~BasePlus()
    {
        cout << "~baseplus\n";
    }

    void func() override
    {
        cout << "baseplus func\n";
    }


};

int main()
{
    Base*p = new BasePlus;
    p->func();
    delete p;

    return 0;
}

output:

baseplus func

我的理解是也应该输出 ~base,但实际并没有,有点想不明白为什么?

阅读 1.7k
1 个回答

这实际是一个 undefined behavior。

expr.delete#3

In a single-object delete expression, if the static type of the object to be deleted is different from its dynamic type and the selected deallocation function (see below) is not a destroying operator delete, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined. In an array delete expression, if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

含有 UB 的程序什么都可能发生


godbolt 上,是可以打印出 ~base 的。


destroying operator delete

A deallocation function is a destroying operator delete if it has at least two parameters and its second parameter is of type std::destroying_delete_t. A destroying operator delete shall be a class member function named operator delete.

就是长这样的:

struct Bar {
    void operator delete(Bar *p, std::destroying_delete_t) {/*...*/}
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题