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?
Assume delete[] didn't exist, write the code for deleting the array vs deleting only the first element in the array.
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".
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.
Consider:
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.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
anddelete[]
,delete
can be implemented without the overhead needed to correctly implementdelete[]
as well.