[PATCH] c++: __builtin_bit_cast To C array target type [PR103140]
will wray
wjwray@gmail.com
Mon Nov 15 23:32:14 GMT 2021
Yes - direct use of any builtin is not to be encouraged, in user code.
This __builtin_bit_cast patch is intended to encourage experimentation
with array copy semantics now, on truck, in preparation for P1997.
The builtin bit_cast is strictly more powerful than the std::bit_cast
library function that it helps implement, is available in any -std mode
and might also be useful in C, independent of any standardization effort.
The semantics of bit_cast is clear - it's just the resulting rvalue array
itself is unfamiliar and tricky to handle within current language rules.
On Mon, Nov 15, 2021 at 12:21 PM Jakub Jelinek <jakub@redhat.com> wrote:
>
> 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...
>
> Jakub
>
More information about the Gcc-patches
mailing list