Date: Sat, 17 Jan 2026 16:47:07 +0100
> 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.
>
The purpose is to do type punning both at runtime and at compile-time, with
the same code, in such a way that works if your type has padding bits too
(e.g. long double). And yes, bit_cast is the right tool for that.
> So should std::bit_cast() itself be amended to always clear the bits? When
> would we not want that?
>
That's certainly an option. I discuss that in
https://isocpp.org/files/papers/D3969R0.html#why-not-make-std::bit_cast_zero_padding-the-default-behavior
The issue is mainly that you get differences in behavior between compiler
versions (or even standards, if this is not a DR). This would be a
sharp edge. It also adds cost: an implementation of bit_cast is currently
permitted to copy over the bits from the source in their original state.
Clearing the bits would add cost to existing code. Without two separate
functions, you have no way of opting out of the cost.
> 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.
>
The purpose is to do type punning both at runtime and at compile-time, with
the same code, in such a way that works if your type has padding bits too
(e.g. long double). And yes, bit_cast is the right tool for that.
> So should std::bit_cast() itself be amended to always clear the bits? When
> would we not want that?
>
That's certainly an option. I discuss that in
https://isocpp.org/files/papers/D3969R0.html#why-not-make-std::bit_cast_zero_padding-the-default-behavior
The issue is mainly that you get differences in behavior between compiler
versions (or even standards, if this is not a DR). This would be a
sharp edge. It also adds cost: an implementation of bit_cast is currently
permitted to copy over the bits from the source in their original state.
Clearing the bits would add cost to existing code. Without two separate
functions, you have no way of opting out of the cost.
Received on 2026-01-17 15:47:20
