This question was asked as part of Does delete[] deallocate memory in one shot after invoking destructors? but moved out as a separate question.
It seems (Correct me if wrong) that the only difference between delete
and delete[]
is that delete[]
will get the array size information and invoke destructors on all of them, while delete
will destruct the only first one. In particular, delete
also has access to the info on how much total memory is allocated by new[]
.
If one doesn't care about destructing the dynamically allocated array elements, and only care that the memory allocated either by new
or new[]
be deallocated, delete
seems to be able to do the same job.
This How does delete[] "know" the size of the operand array? question's accepted answer has one comment from @AnT and I quote
Also note that the array element counter is only needed for types with non-trivial destructor. For types with trivial destructor the counter is not stored by new[] and, of course, not retrieved by delete[]
This comment suggests that in general delete
expression knows the amount of the entire memory allocated and therefore knows how much memory to deallocate in one shot in the end, even if the memory hold an array of elements. So if one writes
auto pi = new int[10];
...
delete pi;
Even though the standard deems this as UB, on most implementations, this should not leak memory (albeit it is not portable), right?