通过指向其基址的指针删除 POD 对象是否安全?

Is it safe to delete a POD object by a pointer to its base?

实际上我在考虑普通可破坏的对象,而不仅仅是 POD(我不确定 POD 是否可以有基础 class)。

当我从 cppreference 阅读对 is_trivially_destructible 的解释时,我注意到:

Storage occupied by trivially destructible objects may be reused without calling the destructor.

所以,这样做是安全的:

struct A {
  int a;
};
struct B : A {
  int b;
};
int main() {
  A* a = new B;
  delete a;
}

B::~B() 不会被调用 - 并且 AFAIK(如果我错了请更正)整个内存将被释放。 B::~B() 肯定是微不足道的。

我知道这段代码很难闻,但我的问题只是关于这段代码的安全性...

不,这是不允许的。 [expr.delete]/p3,强调我的:

In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, 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.

事实上,委员会最近 rejected a proposal to make deleting a POD via a pointer-to-base well-defined