[PATCH] c++: __builtin_bit_cast To C array target type [PR103140]

Jakub Jelinek jakub@redhat.com
Mon Nov 15 17:21:04 GMT 2021

On Mon, Nov 15, 2021 at 12:12:22PM -0500, will wray via Gcc-patches wrote:
> One motivation for allowing builtin bit_cast to builtin array is that
> it enables direct bitwise constexpr comparisons via memcmp:
>     template<class A, class B>
>     constexpr int bit_equal(A const& a, B const& b)
>     {
>       static_assert( sizeof a == sizeof b,
>           "bit_equal(a,b) requires same sizeof" );
>       using bytes = unsigned char[sizeof(A)];
>       return __builtin_memcmp(
>              __builtin_bit_cast(bytes,a),
>              __builtin_bit_cast(bytes,b),
>              sizeof(A)) == 0;
>     }

IMNSHO people shouldn't use this builtin directly, and we shouldn't
encourage such uses, the standard interface is std::bit_cast.

For the above, I don't see a reason to do it that way, you can
instead portably:
  struct bytes { unsigned char data[sizeof(A)]; };
  bytes ab = std::bit_cast(bytes, a);
  bytes bb = std::bit_cast(bytes, a);
  for (size_t i = 0; i < sizeof(A); ++i)
    if (ab.data[i] != bb.data[i])
      return false;
  return true;
- __builtin_memcmp isn't portable either and memcmp isn't constexpr.

If P1997 is in, it is easy to support it in std::bit_cast and easy to
explain what __builtin_bit_cast does for array types, but otherwise
it is quite unclear what it exactly does...


More information about the Gcc-patches mailing list