4

I know this is not allowed by C++ standard and it does not compile on gcc, but I want to know why it works in Visual Studio.

#include <iostream>

struct A
{
    A()
    {
        std::cout << "A()" << std::endl;
    }
    ~A()
    {
        std::cout << "~A()" << std::endl;
    }
};

int main()
{
    int n;
    std::cin >> n;
    A* arr = new A[n];
    delete[n] arr;
}

It behaves the same with delete[] arr;, delete[n+5] arr;, delete[n/2] arr;, delete[-54] arr; and even delete[A{}] arr;.

Lassie
  • 853
  • 8
  • 18
  • 2
    As you said, that is not allowed in standard C++, the brackets must be empty. `placement-new` allows additional parameters to be passed to `new`, but `delete` does not. If VS allows non-empty brackets on `delete[]` then that must be a Microsoft-specific extension, but I do not see it documented on MSDN, either [here](https://docs.microsoft.com/en-us/cpp/cpp/new-and-delete-operators?view=vs-2019), [here](https://docs.microsoft.com/en-us/cpp/cpp/delete-operator-cpp?view=vs-2019), or [here](https://docs.microsoft.com/en-us/cpp/build/reference/microsoft-extensions-to-c-and-cpp?view=vs-2019). – Remy Lebeau Feb 04 '20 at 00:56
  • 1
    I don't see it too, that's why I created this question. – Lassie Feb 04 '20 at 00:58
  • 2
    With Visual Studio 2019 (version 16.4.4) I get a warning `warning C4208: nonstandard extension used: delete [exp] - exp evaluated but ignored` – Blastfurnace Feb 04 '20 at 05:52
  • It would be interesting to know the reasoning for introducing this in the first place. MSDN: https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-4-c4208?redirectedfrom=MSDN&view=vs-2019 and what it does: https://stackoverflow.com/questions/1747976/c-array-delete-operator-syntax/1747994#1747994 – J.R. Feb 04 '20 at 06:30

1 Answers1

1

As far as I'm concerned you should use delete[] arr. Otherwise you may get Compiler Warning C4208.

With Microsoft extensions /Ze, you can delete an array using a value within brackets with the delete operator. The value is ignored. Such values are invalid under ANSI compatibility /Za.

If you try to use /Za, you'll get Compiler Error C2203.

For more details I suggest you could refer to the link: C++ array delete operator syntax

Jeaninez - MSFT
  • 3,210
  • 1
  • 5
  • 20
  • `/Za` is only intended for C mode, as per Microsoft's own docs. It does not even make sense that it changes behavior for some C++ extension. One wonders... – Acorn Feb 04 '20 at 07:45