为什么我们甚至需要“删除[]"?操作员? [英] Why do we even need the "delete[]" operator?

查看:46
本文介绍了为什么我们甚至需要“删除[]"?操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个困扰我一段时间的问题.我一直认为 C++ 的设计应该使 delete 运算符(不带括号)与 new[] 运算符一起工作.

This is a question that's been nagging me for some time. I always thought that C++ should have been designed so that the delete operator (without brackets) works even with the new[] operator.

在我看来,写这个:

int* p = new int;

应该相当于分配一个包含 1 个元素的数组:

should be equivalent to allocating an array of 1 element:

int* p = new int[1];

如果这是真的,delete 操作符总是可​​以删除数组,我们就不需要 delete[] 操作符.

If this was true, the delete operator could always be deleting arrays, and we wouldn't need the delete[] operator.

在 C++ 中引入 delete[] 运算符有什么原因吗?我能想到的唯一原因是分配数组的内存占用很小(您必须将数组大小存储在某处),因此区分 deletedelete[] 是一个小的内存优化.

Is there any reason why the delete[] operator was introduced in C++? The only reason I can think of is that allocating arrays has a small memory footprint (you have to store the array size somewhere), so that distinguishing delete vs delete[] was a small memory optimization.

推荐答案

这样可以调用各个元素的析构函数.是的,对于 POD 数组,没有太大区别,但在 C++ 中,您可以拥有具有非平凡析构函数的对象数组.

It's so that the destructors of the individual elements will be called. Yes, for arrays of PODs, there isn't much of a difference, but in C++, you can have arrays of objects with non-trivial destructors.

现在,你的问题是,为什么不让 newdelete 表现得像 new[]delete[] 并去掉 new[]delete[]?我会回到 Stroustrup 的设计与进化"一书中,他说如果你不使用 C++ 特性,你就不应该为它们付费(至少在运行时).现在的情况是,newdelete 的行为与 mallocfree 一样有效.如果 delete 具有 delete[] 的含义,那么在运行时会有一些额外的开销(正如 James Curran 指出的那样).

Now, your question is, why not make new and delete behave like new[] and delete[] and get rid of new[] and delete[]? I would go back Stroustrup's "Design and Evolution" book where he said that if you don't use C++ features, you shouldn't have to pay for them (at run time at least). The way it stands now, a new or delete will behave as efficiently as malloc and free. If delete had the delete[] meaning, there would be some extra overhead at run time (as James Curran pointed out).

这篇关于为什么我们甚至需要“删除[]"?操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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