After I do, say
Foo* array = new Foo[N];
I've always deleted it this way
delete[] array;
However, sometimes I've seen it this way:
delete[N] array;
As it seems to compile and work (at least in msvc2005), I wonder: What is the right way to do it? Why does it compile the other way, then?
You can check this MSDN link: delete[N] operator. The value is ignored.
EDIT I tried this sample code on VC9:
int test()
{
std::cout<<"Test!!\n";
return 10;
}
int main()
{
int* p = new int[10];
delete[test()] p;
return 0;
};
Output is: Test!!
So the expression is evaluated but the return value is ignored. I am surprised to say the least, I can't think of a scenario why this is required.
delete [N] array
is invalid. It's not defined in the C++ standard: section 5.3.5 defines a delete expression as either delete expr
or delete [] expr
, and nothing else. It doesn't compile on gcc (version 4.1.2). As to why it compiles in Visual C++: ask Microsoft.
delete[] array;
is the correct form.
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