Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::bit_cast allowed on pointers?

std::bit_cast is advertised as the safe alternative to type-punning via reinterpret_cast. However, I see very often that people just blindly replace reinterpret_cast with bit_cast and calls it a day:

float x{};
-int y = *reinterpret_cast<int*>(&x);
+int y = *std::bit_cast<int*>(&x);

Which is not just obviously wrong, but entirely bypasses all compiler and linter warnings. I have seen std::bit_cast hiding an illegal combination of both reinterpret_cast plus const_cast, which would be totally banned in code review.

So, why did they allow this? What is the use case of std::bit_cast on pointers?

like image 228
user1011113 Avatar asked Aug 09 '26 08:08

user1011113


1 Answers

I found now the paper introducing std::bit_cast:

https://www.open-std.org/jtc1/sc22/WG21/docs/papers/2016/p0476r1.html#r0r1

Version R0 did have logic to prevent it from being used on pointers, but it was dropped in R1 with following comment:

The pointer-forbidding logic was removed. It was initially there to help developers when a better tool is available, but it’s easily worked around (e.g. with a struct containing a pointer). Note that this doesn’t prevent constexpr versions of bit_cast: the implementation is allowed to error out on bit_cast of pointer.

With voting:

bit_cast should allow pointer types in To and From. SF F N A SA 4 5 4 2 1

My interpretation is then that std::bit_cast with pointers is useful because it can be used in constexpr contexts, unlike reinterpret_cast. Adding extra safety is not useful either because it's easily worked around anyway.

My understanding is also that it's not the responsibility of C++ as a language to prevent misuse of libraries - compilers or linters should do that instead.

like image 172
user1011113 Avatar answered Aug 11 '26 23:08

user1011113



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!