Possible Duplicate:
( POD )freeing memory : is delete[] equal to delete ?
When I was taught C++, this was a long time ago. I was told to never use delete
but delete[]
as performing delete[]
on a single object will be equivalent to delete
. Knowing not to trust teachers too much I wonder, Is this true?
Is there ever a reason to call delete
instead of delete[]
?
I've scanned the possibly related questions in SO, but haven't found any clear answer.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer.
new[] also stores the number of elements it created in the memory block (independently of malloc ), so that later delete[] can retrieve and use that number to call the proper number of destructors.
The operand of delete must be a pointer returned by new , and cannot be a pointer to constant. Deleting a null pointer has no effect. The delete[] operator frees storage allocated for array objects created with new[] . The delete operator frees storage allocated for individual objects created with new .
Yes. For each time a new[] expression is executed, there must be exactly one delete[] . If there is no delete[] , then there is a leak.
From the standard (5.3.5/2) :
In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined.
In the second alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression. If not, the behavior is undefined.
So no : they are in no way equivalent !
delete []
is "vector delete" and corresponds to vector new, i.e. new[]
.
You must use the matching pair of allocators. E.g. malloc/free
, new/delete
, new[]/delete[]
, else you get undefined behavior.
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