Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ array delete operator syntax

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?

like image 439
raven Avatar asked Nov 17 '09 10:11

raven


3 Answers

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.

like image 148
Naveen Avatar answered Oct 12 '22 23:10

Naveen


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.

like image 27
Mike Seymour Avatar answered Oct 13 '22 01:10

Mike Seymour


delete[] array; is the correct form.

like image 35
laura Avatar answered Oct 12 '22 23:10

laura