The difference between delete and delete[] in C++
You delete []
when you new
ed an array type, and delete
when you didn't. Examples:
typedef int int_array[10];
int* a = new int;
int* b = new int[10];
int* c = new int_array;
delete a;
delete[] b;
delete[] c; // this is a must! even if the new-line didn't use [].
delete
and delete[]
are not the same thing! Wikipedia explains this, if briefly. In short, delete []
invokes the destructor on every element in the allocated array, while delete
assumes you have exactly one instance. You should allocate arrays with new foo[]
and delete them with delete[]
; for ordinary objects, use new
and delete
. Using delete[]
on a non-array could lead to havoc.
- If you allocate with malloc(), you use free()
- If you allocate with new you use delete
- If you allocate with new[] you use delete[]
- If you construct with placement-new you call the destructor direct
- If it makes sense to use vector rather than new[] then use it
- If it makes sense to use smart-pointers then use them and don't bother to call delete (but you'll still need to call new). The matching delete will be in the smart-pointer.
https://isocpp.org/wiki/faq/freestore-mgmt