C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Fixing std::bit_cast padding bit issues

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Thu, 22 Jan 2026 11:35:58 -0500
On Thu, Jan 22, 2026 at 11:19 AM Ell via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Thursday, January 22nd, 2026 at 4:55 PM, Lénárd Szolnoki <
> cpp_at_[hidden]> wrote:
> > On 21 January 2026 21:10:28 GMT, Ell via Std-Proposals
> std-proposals_at_[hidden] wrote:
> > > On Wednesday, January 21st, 2026 at 8:03 PM, Jan Schultke via
> Std-Proposals std-proposals_at_[hidden] wrote:
> > > > On Wed, 21 Jan 2026 at 19:00, Thiago Macieira thiago_at_[hidden]
> wrote:
> > > > > On Wednesday, 21 January 2026 09:41:12 Pacific Standard Time Jan
> Schultke wrote:
> > > > >
> > > > > > > > Because the result of std::bit_cast has unspecified padding
> bits, so x =
> > > > > > >
> > > > > > > Unless we change std::bit_cast, which is what I am proposing.
> > > >
> > > > [...] it's a function and returns by value, so it's limited by the
> calling conventions for the platform, and whether those preserve padding
> (they usually don't) [...]


> Like I said in the other mail, I was thinking about types that aren't
> covered by this exemption (which could even be trivially copyable,
> contrived as it is). Theoretically, they should preserve padding under RVO,
> but in practice they don't <https://godbolt.org/z/Kn86Ko4Wf>. Like Jan
> said, changing that would affect ABI, so if anything, it's probably a (not
> very serious) defect.
>

Okay, everyone's missing the point. (Especially Jan.)
Thiago and others have repeatedly proposed that *std::bit_cast should clear
the padding bits of the input type*.
Nobody cares about padding bits in the *output* type; we *cannot* care
about those bits, by definition, because they are padding. Jan doesn't want
to care about them, either. His example, AIUI, is basically
    using Dest = std::array<char,16>;
    using Source = long double;
    Source s = 3.14;
    Dest d = std::bit_cast<Dest>(s);
    // Now inspect the bits of `d`. None of them are padding, because `d`
has no padding bits. Those bits which were padding in `s` *should* be
zeroed in `d`, because bit_cast *should* clear padding bits.
That's all. Obviously if you do it the other way around, then you don't get
anything meaningful or different:
    Dest d = {};
    Source s = std::bit_cast<Source>(d);
    // Now inspect the bits of `s`, a long double. The padding bits are
indeterminate, of course. The others are preserved. This is the same as
today's std::bit_cast.

There are no ABI issues and no backward-compatibility issues. It would not
totally surprise me if vendors are actually already doing this today,
because doing anything else (at constexpr time, anyway) would be harder.

–Arthur

Received on 2026-01-22 16:36:17