C++ Logo

std-proposals

Advanced search

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

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Fri, 16 Jan 2026 19:42:31 +0300
On 16 Jan 2026 18:36, Thiago Macieira via Std-Proposals wrote:
> On Friday, 16 January 2026 07:17:40 Pacific Standard Time Jan Schultke via Std-
> Proposals wrote:
>> The reason is also that granting the implementation the freedom to not copy
>> around padding bytes is an optimization opportunity, and relying on the
>> values of padding bytes is a massive (security-critical) bug anyway. There
>> are still floating-point types where certain representations result in CPU
>> traps when used in an operation, if you find that to be more convincing of
>> a reason.
>>
> ...
>> Because the source could also not be used. For all intents and purposes,
>> padding bits are eternally indeterminate quantum bits, and querying their
>> value results in your CPU exploding.
>>
> ...
>> It is doing god knows what. When a type has four value bytes and four
>> padding bytes, moving it around may be done via 32-bit register move.
>> Whether that preserves the upper 32 bits or wipes them (like on x86) is a
>> CPU architecture implementation detail, and not anything you can portably
>> rely on.
>
> This is a long way of saying that
>
> template <typename T> T clear_padding(const T &);
>
> isn't useful because the the padding bits can be come indeterminate again
> before you can make use of the result, including passing to std::bit_cast.

If you're referring to my definition of clear_padding then this is not
how I defined it, precisely because of this. My definition was:

  template< typename T >
  void clear_padding(T& val) noexcept;

i.e. the function would operate on the existing object in-place. Then,
that same object is passed to bit_cast by reference.

> That is, we require a way to clear *and* cast to a type that has no padding
> bits in one operation. So we go back to either std::bit_cast_zero_padding or
> modifying std::bit_cast behaviour.
Not necessarily, see above.

Received on 2026-01-16 16:42:33