Consider:
delete new std :: string [2];
delete [] new std :: string;
Everyone knows the first is an error. If the second wasn't an error, we wouldn't need two distinct operators.
Now consider:
std :: unique_ptr <int> x (new int [2]);
std :: unique_ptr <int> y (new int);
Does x
know to use delete[]
as opposed to delete
?
Background: this question floated through my head when I thought array type qualification of pointers would be a handy language feature.
int *[] foo = new int [2]; // OK
int * bar = new int; // OK
delete [] foo; // OK
delete bar; // OK
foo = new int; // Compile error
bar = new int[2]; // Compile error
delete foo; // Compile error
delete [] bar; // Compile error
new int[2]
ought to return a value of typeint (*)[2]
. Anyway, it's too late to fix all the problems with native arrays, but you can usestd::array
and avoid ever having to deal with them.std::array
works like native arrays should work and you never have to usenew[]
ordelete[]
. – Ratanstd::array
. You can donew int[n]
, but you can't dostd::array<int,n>
. (Unlessn
is known at compile time). But still, I avoid native arrays!# – Tavishstd::vector
if you need dynamic allocation. – Ratan