你为什么要这样写? (有意不在数组上使用delete []) [英] Why would you write something like this? (intentionally not using delete [] on an array)

查看:92
本文介绍了你为什么要这样写? (有意不在数组上使用delete [])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶尔遇到这种代码 - 我怀疑创建者是/恐怕表删除将迭代表和性能成本(这不会做任何方式)... ...

I came across this kind of code once in a while - I suspect the creator is/was afraid that table delete would iterate over the table and "cost performance" (which imho will not be done either way)... is there any real benefit one might get/consider/imagine from not using the the table delete here?

myClass** table = new myClass* [size];
... //some code that does not reallocate or change the value of the table pointer ;)
delete table; // no [] intentionally


推荐答案

写得像这样和一个严重的原因,从来没有这样做。

There's really no reason to write like that and a serious reason to never do so.

这是真的,对于类型有微不足道的析构函数(像你的情况下的原始指针),没有必要知道实际因此编译器可能决定将 new [] delete [] 映射到 / em>以减少开销。如果它决定这种方式,你不能停止它,没有采取额外的步骤,所以这个编译器优化会发生,而不会通知,将是免费的。

It's true that for types with trivial destructors (like raw pointers in your case) there's no need to know the actual number of elements in the array and so the compiler might decide to map new[] and delete[] onto new and delete to reduce the overhead. If it decides this way you can't stop it without extra steps taken, so this compiler optimization will take place without your notice and will be free.

有人使用您的代码可能希望重载全局运算符删除(和新的[] 删除[] )。如果发生这种情况,你会遇到很大的麻烦,因为这是你真正需要的删除删除[] 之间的区别。

At the same time someone using your code might wish to overload the global operators new and delete (and new[] and delete[] as well). If that happens you run into big trouble because this is when you may really need the difference between the delete and delete[].

添加到这个编译器依赖的优化是不可移植的。

Add to this that this compiler-dependent optimization is unportable.

这是这样的情况下, / em>删除,但风险很大的时候依赖未定义的行为。

So this is the case when you get no benefits displacing delete[] with delete but risk big time relying into undefined behaviour.

这篇关于你为什么要这样写? (有意不在数组上使用delete [])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆