C++ Logo

std-proposals

Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Fri, 30 Jun 2023 21:07:54 -0400
On Fri, Jun 30, 2023 at 8:34 PM 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?
>
> (The special case where N is zero would be excluded from the requirement, obviously).
>
> A lot of people are surprised when I tell them that the standard doesn't already provide this guarantee.
>
> 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.

The principal motivation I have is `bit_cast`. You cannot `bit_cast`
from/to language arrays, but you can do it to `std::array`... except
that there's no *guarantee* that you can.

You ought to be able to, for any trivially-copyable type `T`, perform
`bit_cast<std::array<std::byte, sizeof(T)>>(some_t)` and be guaranteed
that this will work. And vice-versa.

Received on 2023-07-01 01:08:03