C ++ Syntax Operator Syntax

After that say

Foo* array = new Foo[N];

I always deleted it that way

delete[] array;

However, sometimes I saw it like this:

delete[N] array;

It seems to compile and work (at least in msvc2005), I wonder: What is the right way to do this? Why does it compile in a different way?

+7
c ++ arrays delete-operator
source share
7 answers

You can check this MSDN link: delete the [N] statement . 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; }; 

Exit: Test !!

So, the expression is evaluated, but the return value is ignored. I am surprised, to say the least, I can not come up with a script why this is required.

+13
source share

delete [N] array not valid. It is not defined in the C ++ standard: section 5.3.5 defines a delete expression as delete expr or delete [] expr , and nothing more. It does not compile on gcc (version 4.1.2). As to why it compiles in Visual C ++: contact Microsoft.

+10
source share

delete[] array; - the correct form.

+5
source share

Whether the second case is correct or not, I would recommend using the first, as it is less error prone.

Visual Studio compiles many things that it should not do.

+5
source share

The correct way is to do delete[] array; . I did not even know that delete[N] array; will compile (and I doubt it should).

+4
source share

The first point: there is practically no reason to use the new or delete array form to start with - use std :: vector (or some other container) instead.

Secondly: in the dark C ++ times, you had to specify the size of the array you were deleting, so if you used x = new T[N] , the corresponding deletion was delete [N] x . The requirement to explicitly specify the size has been removed a long time ago, but some compilers (especially those that care about backward compatibility with ancient code) still allow this.

If you really need to stay compatible with the ancient compiler (which is 20 years old or so), you should not use it. Again, if you do not need to remain compatible with such an old compiler, it does not support standard containers, you should not use the new or delete array form in the first place. Just stop!

+4
source share

if it works, this is a non-standard extension.

 delete [] array; 

- the correct form.

 delete array; 

sometimes also works, but implementation dependent (therefore incorrect).

-2
source share

All Articles