Reputation: 64328
In C++, if you want to dynamically allocate an array, you can do something like this:
int *p;
p = new int[i]; // i is some number
However, to delete the array, you do...
delete[] p;
Why isn't it delete p[]
? Wouldn't that be more symmetrical with how it was originally created? What is the reason (if there is any) why the language was designed this way?
Upvotes: 16
Views: 1004
Reputation: 3166
Because array decays to pointer when passing as parameter to function (or operator). So delete p[] would be simply equivalent to delete p.
[edit] We may think of delete as of special template operator. The operator should be able to distingish between p and p[] to pick the right "specialization" (non-array or array deletion). However, template argument deduction rules make this choice impossible (due to array decaying we can't distingish between p[] and p when deducing the argument).
So we can't use operator with name delete for both casees and need to introduce another operator delete[] with diffrent name (suffix [] can be treated as part of operator's name) for array case.
[edit 2] Note. delete p[] is not valid sintax at all according to the current standard. The reasoning above only shows problems that could araise if we would try to interpret delete p[] using existing c++ concepts.
Upvotes: 2
Reputation: 73580
One reason could be to make these cases more distinct.
int ** p;
delete[] p
delete p[1];
If it were delete p[]
then a one character error would have pretty nasty consquences.
Upvotes: 29