raven
raven

Reputation: 2564

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?

Upvotes: 7

Views: 3270

Answers (7)

Jerry Coffin
Jerry Coffin

Reputation: 490108

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!

Upvotes: 4

Naveen
Naveen

Reputation: 73443

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.

Upvotes: 13

Nicholaz
Nicholaz

Reputation: 1429

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).

Upvotes: -2

Mike Seymour
Mike Seymour

Reputation: 254431

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.

Upvotes: 10

Mykola Golubyev
Mykola Golubyev

Reputation: 59814

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.

Upvotes: 5

sbi
sbi

Reputation: 224049

The right way is to do delete[] array;. I didn't even know delete[N] array; would compile (and I doubt it should).

Upvotes: 4

laura
laura

Reputation: 7332

delete[] array; is the correct form.

Upvotes: 5

Related Questions