Why do we even need the "delete[]" operator?
Damn, I missed the whole point of question but I will leave my original answer as a sidenote. Why we have delete[]
is because long time ago we had delete[cnt]
, even today if you write delete[9]
or delete[cnt]
, the compiler just ignores the thing between []
but compiles OK. At that time, C++ was first processed by a front-end and then fed to an ordinary C compiler. They could not do the trick of storing the count somewhere beneath the curtain, maybe they could not even think of it at that time. And for backward compatibility, the compilers most probably used the value given between the []
as the count of array, if there is no such value then they got the count from the prefix, so it worked both ways. Later on, we typed nothing between []
and everything worked. Today, I do not think delete[]
is necessary but the implementations demand it that way.
My original answer (that misses the point):
delete
deletes a single object. delete[]
deletes an object array. For delete[]
to work, the implementation keeps the number of elements in the array. I just double-checked this by debugging ASM code. In the implementation (VS2005) I tested, the count was stored as a prefix to the object array.
If you use delete[]
on a single object, the count variable is garbage so the code crashes. If you use delete
for an object array, because of some inconsistency, the code crashes. I tested these cases just now !
"delete
just deletes the memory allocated for the array." statement in another answer is not right. If the object is a class, delete
will call the DTOR. Just place a breakpoint int the DTOR code and delete
the object, the breakpoint will hit.
What occurred to me is that, if the compiler & libraries assumed that all the objects allocated by new
are object arrays, it would be OK to call delete
for single objects or object arrays. Single objects just would be the special case of an object array having a count of 1. Maybe there is something I am missing, anyway.
It's so that the destructors of the individual elements will be called. Yes, for arrays of PODs, there isn't much of a difference, but in C++, you can have arrays of objects with non-trivial destructors.
Now, your question is, why not make new
and delete
behave like new[]
and delete[]
and get rid of new[]
and delete[]
? I would go back Stroustrup's "Design and Evolution" book where he said that if you don't use C++ features, you shouldn't have to pay for them (at run time at least). The way it stands now, a new
or delete
will behave as efficiently as malloc
and free
. If delete
had the delete[]
meaning, there would be some extra overhead at run time (as James Curran pointed out).