C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Thu, 22 Jan 2026 22:09:22 -0800
On Thursday, 22 January 2026 21:41:28 Pacific Standard Time Jan Schultke wrote:
> > The important question is that of behaviour. So long as it behaves as if
> > the
> > bits have been cleared, any as-if transformation is fine.
>
> So if you put a piece of code (maybe small, maybe large) between
> std::clear_padding and std::popcount, the compiler may not optimize
> std::popcount the way you want and give you an unspecified result?

No.

So long as the variable isn't assigned to, it should stay with bits cleared,
either concretely as a region of memory or logically so.

> I think Sebastian is asking the right question here; you should be able to
> put an arbitrary distance between std::clear_padding and std::popcount and
> retain the semantics.

Agreed.

> My intuition is that you could get those guarantees if you ran
> std::clear_padding, std::memcpy to a byte array, and then std::bit_cast out
> of a byte array into std::uint128_t. However, that forces compilers to
> permanently spill objects from registers (such as function parameters
> passed via register) into memory when std::clear_padding is used on them
> because it's possible that someone will later read the padding bits. Maybe
> merely the possibility that std::clear_padding is run in some opaque
> function causes pessimizations. This would definitely need to be
> investigated when proposing a std::clear_padding function.

No, it does not. Again, the only thing that matters is the behaviour.

The compiler does not have to make the variable concrete in memory.

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

Received on 2026-01-23 06:09:31