通过指向其基址的指针删除POD对象是否安全? [英] Is it safe to delete a POD object by a pointer to its base?
问题描述
实际上,我正在考虑简单的可破坏对象,不仅仅是关于 POD (我不确定POD可以有基类)。
Actually I am thinking about trivially destructible objects, not only about POD (I am not sure POD can have base class).
When I read this explanation for is_trivially_destructible from cppreference I notice this:
可被重复使用的可破坏的对象的存储可以被重用。调用析构函数。
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 c $ c>不会被调用 - 和AFAIK(请更正,如果我错了)整个内存将被释放。
B ::〜B()
肯定是微不足道的。
我知道这个代码气味不好,问题只是关于这个代码的安全性...
I know this code smells badly, but my question is only about safeness of this code...
推荐答案
不,这是不允许的。 [expr.delete] / p3,emphasis mine:
No, this is not allowed. [expr.delete]/p3, emphasis mine:
在第一个选项要被删除的
对象的静态类型不同于其动态类型,静态
类型应该是被删除的
的对象的动态类型的基类;静态类型应具有虚拟析构函数或
行为未定义。
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.
事实上,委员会最近拒绝 通过指针到底层明确定义删除POD的建议。
In fact, the committee fairly recently rejected a proposal to make deleting a POD via a pointer-to-base well-defined.
这篇关于通过指向其基址的指针删除POD对象是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!