C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Wed, 21 Jan 2026 08:01:26 -0800
On Tuesday, 20 January 2026 20:43:27 Pacific Standard Time Jan Schultke wrote:
> > 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.

There are exactly zero padding bits in an array of bytes (unsigned char), by
definition.

> 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.

That's exactly what I am proposing: that the std::bit_cast function, however
it is implemented, write zero for padding bits of its input. That includes
entire empty structs, if it is all padding.

> 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.

I don't see why.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel Data Center - Platform & Sys. Eng.

Received on 2026-01-21 16:01:35