Search code examples
c++arraysdelete-operator

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?


Solution

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