C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Sat, 17 Jan 2026 07:21:02 -0800
On Saturday, 17 January 2026 06:09:00 Pacific Standard Time Jan Schultke via
Std-Proposals wrote:
> I have yet to hear any attempt at an argument for why we would want a
> clear_padding utility rather than a bit_cast_zero_padding utility. As I've
> said, padding bits are very easily lost. It also requires expert-level
> knowledge to understand when padding bits have some specified value and
> when they revert back to indeterminate or erroneous value. A clear_padding
> utility also would not work for constant evaluation.

I agree with not seeing the value of clear_padding. Even if there is a path to
stably getting those bits cleared in order to make use of the non-padded
value, it's fragile. But more to the point: what's the purpose of having a T
with its padding bits cleared? The intent of clearing those bits must be that
one wants to observe them, and in T itself, they can't. Therefore, I argue
that the operation to clear the bits must transform the type into something
else where the bits could be observed - that is a bit_cast operation.

> That being said, I'm not strongly opposed to making bit_cast preserve the
> values of padding bits at run-time. However, that doesn't really solve the
> problem that I set out to fix here. Those padding bits are almost certainly
> going to be erroneous or indeterminate if the user doesn't use
> clear_padding, and clear_padding doesn't really work during constant
> evaluation without substantial changes to implementations.
>
> The clear_padding + bit_cast idiom encourages the user to write the wrong
> kind of code. If you forget clear_padding, you may get undefined behavior,
> and what is currently a degenerate form of bit_cast that we could reject at
> compile time (because it always produces UB) becomes undiagnosable; the
> user could have run bit_cast expecting the padding bits to be copied, and
> the compiler has no way of knowing whether that's the intent. Very sharp
> edge!

So should std::bit_cast() itself be amended to always clear the bits? When
would we not want that?

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

Received on 2026-01-17 15:21:13