C++ Logo

std-proposals

Advanced search

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

From: Jan Schultke <janschultke_at_[hidden]>
Date: Wed, 21 Jan 2026 05:43:27 +0100
>
> That said, if there is a need, std::clear_padding() could be implemented
> by:
>
> using Tmp = std::array<unsigned char, sizeof(T)>;
> Tmp tmp = std::bit_cast<Tmp>(src); // or std::bit_cast_clear_padding
> src = std::bit_cast<T>(tmp);
>
> We can hope the compilers see this passage through a temporary and simply
> clear the bits.
>

That cannot work. std::bit_cast_clear_padding would clear the padding bits
in the input that would have otherwise resulted in an indeterminate output,
but the padding bits of the output are unspecified. Due to ABI constraints,
unless std::bit_cast has custom ABI, that is set in stone.

Consider that when returning an empty struct from any function, including
std::bit_cast, the ABI on some platforms is to not pass anything into any
register (nor spill into memory), so padding bits don't exist. Even if the
input to std::bit_cast was a zeroed byte array, that has no impact on the
result. I suppose this could be avoided if we said that std::bit_cast was
not a function in the first place; the intrinsic __builtin_bit_cast is not
constrained by ABI.

Ergo, if you want something that clears padding in-place, that requires a
std::clear_padding function, unless you treat std::bit_cast magically and
give it custom ABI.

Received on 2026-01-21 04:43:43