C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Fri, 16 Jan 2026 09:06:45 -0800
On Friday, 16 January 2026 08:42:31 Pacific Standard Time Andrey Semashev via
Std-Proposals wrote:
> 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.

I still think that's too fragile, because the reloading of val from where it
was stored in memory may reintroduce indeterminate padding bits.

>From the abstract machine's perspective, the padding bits may suddenly change
out of thin air, without an operation in the memory location.

Concretely, imagine one has a wrapper function around std::bit_cast, in order
to support pre-C++20 (not to mention that std::bit_cast itself is a function,
not the intrinsic). Depending on the optimisation levels, the compiler may
load and store the value one or more times from memory. And depending on how
it chooses to do that, it may forego writing the padding bits to memory in one
of the destinations.

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

Received on 2026-01-16 17:06:52