Why is there a delete[] in C++?

不想你离开。 提交于 2019-12-12 08:35:13

问题


Why is there a delete[]? From my understanding its to behave differently for arrays. However, why does it really exist? There's only free in C and no free_array. Also in syntax the only difference between delete var and delete []var is the [] which has no params (I'm not telling the length of the array).

So why does delete[] really exist? I know someone will say you can overload delete and delete[] (at least i think that is possible) but lets say we are not overloading it. Why does it exist?


回答1:


Typically, for non-POD classes, a delete[] expression must call destructors on a variable number of class instances that cannot be determined at compile time. The compiler typically has to implement some run time "magic" that can be used to determine the correct number of objects to destroy.

A delete expression doesn't have to worry about this, it simply has to destroy the one object that the supplied pointer is pointing to. Because of this, it can have a more efficient implementation.

By splitting up delete and delete[], delete can be implemented without the overhead needed to correctly implement delete[] as well.




回答2:


If you delete an array, only first object's destructor will be called. delete[] calls destructors of all objects in array and frees array's memory.




回答3:


Assume delete[] didn't exist, write the code for deleting the array vs deleting only the first element in the array.

delete array;        // Deletes first element, oops    
delete &array;       // Deletes first element, oops
delete &array[0];    // Deletes first element

A pointer to an array being an alias for a pointer to the first element of the array is of course an old C "feature".




回答4:


Consider:

int* a = new int[25];
int* b = a;

delete b;  // only deletes the first element

The C++ compiler has no idea whether b points to an array or a single element. Calling delete on an array will only delete the first element.



来源:https://stackoverflow.com/questions/3694333/why-is-there-a-delete-in-c

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