问题
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