This question may sound a bit weird, but I never entirely got why do we need to have 2 different syntax for deleting dynamically allocated memory in C++?
For example,
int *p = new int[10];
delete[] p; // why not just delete p;?
In plain old C, you just use the free
function to release the memory allocated for a pointer, regardless of the number of elements allocated. Of course, C++ is a bit more complicated, as it allows for class types, which invoke their destructor etc. However, I see no impediment in using a single syntax for deleting dynamically allocated memory in C++.
Is there any fundamental reason why it was decided to use 2 versions, delete
and delete[]
?
More than that, most compilers do not even warn you if you use delete
instead of delete[]
, and this creates undefined behaviour.