为什么我们甚至需要"delete []"操作员? [英] Why do we even need the "delete[]" operator?
问题描述
这是一个困扰我一段时间的问题.我一直认为应该设计C ++,以便即使使用"new []"运算符也可以使用"delete"运算符(不带括号).
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 []"运算符有什么理由吗?我能想到的唯一原因是分配数组的内存占用很小(您必须将数组大小存储在某个地方),因此区分删除"与删除[]"是一个小的内存优化.
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.
现在,您的问题是,为什么不让new
和delete
表现得像new[]
和delete[]
并摆脱new[]
和delete[]
?我回头看看Stroustrup的设计与演化"一书,他在书中说,如果您不使用C ++功能,则不必为它们付费(至少在运行时).按照现在的样子,new
或delete
的行为将与malloc
和free
一样有效.如果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).
这篇关于为什么我们甚至需要"delete []"操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!