gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:04:07 25 4
gpt4 key购买 nike

实际上,我在考虑可平凡破坏的物体,而不仅仅是关于 POD (我不确定 POD 是否可以有基类)。

当我阅读关于 is_trivially_destructible 的解释时从 cppreference 我注意到这一点:

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 .

关于c++ - 通过指向其基址的指针删除 POD 对象是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29841845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com