delete vs delete[] [duplicate]

ぐ巨炮叔叔 提交于 2019-12-16 22:12:31

问题


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?

Is there ever a reason to call delete instead of delete[]?

I've scanned the possibly related questions in SO, but haven't found any clear answer.


回答1:


From the standard (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.

So no : they are in no way equivalent !




回答2:


delete [] is "vector delete" and corresponds to vector new, i.e. new[].

You must use the matching pair of allocators. E.g. malloc/free, new/delete, new[]/delete[], else you get undefined behavior.




回答3:


No! you call delete[] when you allocate with new[], otherwise you call delete.

What teacher told you leads to undefined behaviour and, if you are lucky, an application crash.




回答4:


delete is used to delete a single object, while delete[] is used to delete an array of objects. Check this link for more info.



来源:https://stackoverflow.com/questions/4255598/delete-vs-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!