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?
delete is used for one single pointer and delete[] is used for deleting an array through a pointer. This might help you to understand better.
To delete the array or non-array object, we use delete[] and delete operator, respectively. The new keyword allocated the memory in a heap; therefore, we can say that the delete operator always de-allocates the memory from the heap.
Any time you allocate an array of objects via new (usually with the [ n ] in the new expression), you must use [] in the delete statement. This syntax is necessary because there is no syntactic difference between a pointer to a thing and a pointer to an array of things (something we inherited from C).
What is the difference between delete and delete[] in C++? Explanation: delete is used to delete a single object initiated using new keyword whereas delete[] is used to delete a group of objects initiated with the new operator.
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.
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.
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