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 10:00:31 -0800
On Wednesday, 21 January 2026 09:41:12 Pacific Standard Time Jan Schultke
wrote:
> > > Because the result of std::bit_cast has unspecified padding bits, so x =
> >
> > Unless we change std::bit_cast, which is what I am proposing.
>
> It would be an ABI break if you changed that, and compilers would
> essentially have to invent new ABI for all kinds of platforms to make this
> work, so the std::bit_cast that you're proposing is practically
> unimplementable.

Why are you saying that? How is the behaviour of std::bit_cast ABI in the first
place?

> using Tmp = std::array<unsigned char, sizeof(T)>;
> Tmp tmp = std::bit_cast<Tmp>(src); // or std::bit_cast_clear_padding
> std::memcpy(src, &tmp, sizeof(T));
>
> Since byte arrays have no padding bits, there is no issue with padding bits
> in the std::bit_cast result. It's crucial to then memcpy back into src
> rather than using the assignment operator; in that case, I think this can
> clear padding in the source.

Ah, good point.

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

Received on 2026-01-21 18:00:44