C/C++ delete vs delete[] [duplicate]

…衆ロ難τιáo~ 提交于 2020-05-13 11:40:48

问题


Possible Duplicate:
How could pairing new[] with delete possibly lead to memory leak only?
delete vs delete[]

I just started learning C/C++ and I was told to use delete to delete a single object and to use delete [] for an array.

Then I found this website which asks this question

Anything wrong with this code?

T *p = new T[10];
delete p;

Note: Incorrect replies: “No, everything is correct”, “Only the first element of the array will be deleted”, “The entire array will be deleted, but only the first element destructor will be called”.

Which raises the question, what does happen in that block of code? I would have logically thought that it was "Only the first element of the array will be deleted” but it seems not. Can anyone shed some light on this?


回答1:


  • delete: This frees the memory currently allocated by the pointer the delete is performed upon. It only deletes the memory pointed to by the first variable.

  • delete []: This frees the memory allocated for the whole array. An array consists of several variables - delete frees memory only allocated for the first variable, while delete [] does the whole thing.

A good way to think of it is considering delete as an instruction while delete [] as a loop; where the array is looped through and delete is called individually on each variable in the array. This is NOT how it works in reality (the real workings are a bit more complicated), but is a good way to understand the diff.

The destructor is called on all objects, because in some cases such as in the case of an array of objects that contain pointers, calling the destructor on only the first element doesn't free all memory.



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

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