C++ Logo

std-proposals

Advanced search

Re: [std-proposals] promote T[] and deprecate delete[]

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Tue, 01 Jul 2025 23:57:24 +0300
On July 1, 2025 6:26:11 PM Henning Meyer via Std-Proposals
<std-proposals_at_[hidden]> wrote:

> I think there was an (unavoidable) missed opportunity in C++98 when
> new[] and delete[] were introduced.
>
> What we have currently is unchanged since 1998 and very C:
>
> new std::string[8] returns an object of type std::string*. It is
> indistinguishable in its type from the result of new std::string.
>
> When you free it, you must remember that it was allocated via new[] and
> pass it into delete[] instead of delete.
> Calling delete instead of delete[] is undefined behavior and may lead to
> crashes in practice not just memory leaks.
>
> Instead, we could have the following:
>
> new T[n] returns an object of type T[],
>
> we can declare variables of type T[], they have a representation
> identical to T*
>
> objects of type T[] decay to T* similar to array decay,
>
> delete p has the behavior of delete[] when p is of type T[].
>
> This would represent the difference in the type system and not just in
> the logic within functions.
>
>
> I think the state of T[] is very odd in the current language:
>
> variables cannot be declared:
>
> int p[]; // will not compile
>
> struct members can be declared, but this is C (flexible array members)
> and not allowed in strict C++
>
> struct S {
>
> int p[];
>
> };
>
> There are headers written in C that use use this syntax, and these won't
> change to not break existing code.

I don't see how this would help users. Consider something like unique_ptr.
If you can't have T[] members with the proposed new semantics you'll still
need a unique_ptr specialization, and at that point removing the
distinction between delete and delete[] doesn't provide much.

If your goal is to simplify direct usage of delete in users' code then that
doesn't look like a worthy goal as pretty much always you should be using a
smart pointer instead.

Received on 2025-07-01 20:57:28