C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Mandate layout of std::array

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Sat, 1 Jul 2023 09:12:21 +0100
On Sat, 1 Jul 2023, 01:34 Brian Bi via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

> Would folks be interested in a proposal to require std::array<T, N> to
> have the exact same layout as T[N], i.e., no padding before or after the
> internal T[N] data member?
>

Yes please.


> (The special case where N is zero would be excluded from the requirement,
> obviously).
>

Yes.


> A lot of people are surprised when I tell them that the standard doesn't
> already provide this guarantee.
>

It's easy to check that your implementation provides it, and just assume
you'll never encounter one that doesn't:

static_assert(sizeof(std::array<T,N>)==sizeof(T[N]));

But it would be nice to not need that. The spec should be as simple as
saying that the equality above is true for N!=0.


> I can think of some theoretical reasons why this would be useful, such as
> being able to serialize a T[N] and then deserialize it as std::array<T, N>
> using the `std::start_lifetime_as` function. However, I'd like to hear from
> folks here if they would actually benefit from this guarantee in a real
> application. If there's sufficient motivation, I'll write a paper.
>
> I don't think implementations would actually have to do any work to
> conform to this requirement, so my only concern is about whether I can
> provide sufficient motivation to get this proposal through the committee.
>

Guaranteeing something that's always true in practice should be
uncontroversial.



> (Bonus: require std::array<T, N> to be pointer-interconvertible with its
> T[N] member, even when T is not standard-layout. This part of the proposal
> might be a bit more controversial, though; I'm not sure how hard it would
> be for implementors.)
>
>

Received on 2023-07-01 08:12:39