difference between new[ ] / delete [ ] vs new / delete in C++ [duplicate]

﹥>﹥吖頭↗ 提交于 2020-01-30 08:08:04

问题


I have a very quick question: What is the difference between new[ ] / delete [ ] vs new / delete in C++ when it comes to Dynamic memory?

Is new[ ] / delete [ ] not belong to Dynamic memory?


回答1:


new allocates memory for a single item and calls its constructor, and delete calls its destructor and frees its memory.

new[] allocates memory for an array of items and calls their constructors, and delete[] calls their destructors and frees the array memory.




回答2:


Both memory allocation mechanisms work with dynamic memory. The former creates/destroys a single object, the second creates/destroys a run-time sized array of objects. That's the difference.

Other than that, these two mechanisms are two completely separate independent dynamic memory management mechanisms. E.g. allocating an array consisting of 1 element using new[] is not equivalent to simply using new.




回答3:


the difference detween the two is that those with [] are those for array.

The difference is not that visible for the new keyword as there is no error possible

int *i = new int;
Object *array = new Object[100];

however you should make shure to call the good one to make shure destructor are called has the should

delete i; // ok
delete[] array; //ok
delete array; // Careffull, all destructors may not be called


来源:https://stackoverflow.com/questions/28651860/difference-between-new-delete-vs-new-delete-in-c

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