C++ 删除与删除[]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4255598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
delete vs delete[]
提问by onemasse
Possible Duplicate:
( POD )freeing memory : is delete[] equal to delete ?
When I was taught C++, this was a long time ago. I was told to never use delete
but delete[]
as performing delete[]
on a single object will be equivalent to delete
. Knowing not to trust teachers too much I wonder, Is this true?
当我学习 C++ 时,那是很久以前的事了。我被告知永远不要使用delete
但delete[]
因为delete[]
在单个对象上执行将等效于delete
. 知道不要太相信老师,我想知道,这是真的吗?
Is there ever a reason to call delete
instead of delete[]
?
有没有理由打电话delete
而不是delete[]
?
I've scanned the possibly related questions in SO, but haven't found any clear answer.
我已经扫描了 SO 中可能相关的问题,但没有找到任何明确的答案。
回答by icecrime
From the standard (5.3.5/2) :
从标准(5.3.5/2):
In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined.
In the second alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression. If not, the behavior is undefined.
在第一个选择(删除对象)中,删除操作数的值应是指向非数组对象的指针或指向表示此类对象的基类的子对象(1.8)的指针(第 10 条)。 如果不是,则行为未定义。
在第二种选择(删除数组)中,删除操作数的值应该是由前一个数组新表达式产生的指针值。如果不是,则行为未定义。
So no : they are in no way equivalent !
所以不:它们绝不是等价的!
回答by Alex Budovski
delete []
is "vector delete" and corresponds to vector new, i.e. new[]
.
delete []
是“向量删除”,对应于向量新,即new[]
。
You must use the matching pair of allocators. E.g. malloc/free
, new/delete
, new[]/delete[]
, else you get undefined behavior.
您必须使用匹配的分配器对。例如malloc/free
, new/delete
, new[]/delete[]
, 否则你会得到未定义的行为。
回答by Simone
No! you call delete[]
when you allocate with new[]
, otherwise you call delete
.
不!delete[]
分配时调用new[]
,否则调用delete
。
What teacher told you leads to undefined behaviour and, if you are lucky, an application crash.
老师告诉你的会导致未定义的行为,如果幸运的话,还会导致应用程序崩溃。