问题
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?
回答1:
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.
回答2:
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.
回答3:
delete[] array;
is the correct form.
回答4:
Whether second case is right or not I'd recommend to use first one as it less error prone.
Visual Studio compiles a lot of things it shouldn't.
回答5:
The right way is to do delete[] array;
. I didn't even know delete[N] array;
would compile (and I doubt it should).
回答6:
First point: there's almost never a good reason to use the array form of new or delete to start with -- use std::vector (or some other container) instead.
Second: back in the dark ages of C++, you had to specify the size of the array you were deleting, so if you used x = new T[N]
, the matching delete was delete [N] x
. The requirement to explicitly specify the size was removed long ago, but some compilers (especially those that care about backward compatibility with ancient code) still allow it.
Unless you really need to remain compatible with an ancient compiler (one that's 20 years old or so) you shouldn't use it. Then again, unless you need to remain compatible with a compiler so old it doesn't support any standard containers, you shouldn't be using the array form of new or delete in the first place. Just stop!
回答7:
if it works, it's a nonstandard extension.
delete [] array;
is the correct form.
delete array;
will sometimes also work but is implementation dependent (thus wrong).
来源:https://stackoverflow.com/questions/1747976/c-array-delete-operator-syntax