What is wrong with using delete
instead of delete[]
?
Is there something special happening under the covers for allocating and freeing arrays?
Why would it be different from malloc
and free?
The difference is that delete
will only delete the entire memory range, but will only call the destructor for 1 object. delete[]
will both delete the memory and call the destructor for every single object. If you do not use delete[]
for arrays, it's only a matter of time before you introduce a resource leak into your application.
EDIT Update
According to the standard, passing an object allocated with new[]
to delete
is undefined. The likely behavior is that it will act as I described.
Stroustrup talks about the reasons for separate new
/new[]
and delete/
delete[]` operators in "The Design and Evolution of C++" in sections 10.3 through 10.5.1:
new
and delete
was a solution for this;delete
operator is that there needs to be more information than just the pointer in order to determine if the pointer points to the first element of an array or if it just points to a single object. Instead of "complicating the common case of allocating and deallocating individual objects", the delete[]
operator is used to handle arrays. This fits in with the general C++ design philiosophy of "don't pay for what you don't use".Whether this decision was a mistake or not is debatable - either way has good arguments, but we have what we have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With