0

Is reinterpret_cast only made for type punning ?

If I read https://en.cppreference.com/w/cpp/language/reinterpret_cast : "Converts between types by reinterpreting the underlying bit pattern." I understand this cast is made to cast data by bypassing the C++ type system but I can't find other possible uses. But if reinterpret_cast is only useful for type punning, why the documentation doesn't say so ?

Tesla123
  • 319
  • 1
  • 7
  • Even if that were the case (it isn't), why would it say so? It's a reference, not a guide to usefulness. – molbdnilo Feb 09 '23 at 16:46
  • 1
    IMO that's a poor summary sentence on cppreference's part. It makes it sound like `reinterpret_cast` behaves like [`std::bit_cast`](https://en.cppreference.com/w/cpp/numeric/bit_cast) – Brian61354270 Feb 09 '23 at 16:48
  • 1
    At least cppreference does mention that _"reinterpret_cast (or equivalent explicit cast) between pointer or reference types shall not be used to reinterpret object representation in most cases because of the type aliasing rule"_, albeit buried on a different page. – Brian61354270 Feb 09 '23 at 16:50
  • re: type punning, `reinterpret_cast` alone can never be used for type punning (not without UB anyway). The only safe mechanisms for type punning are `std::memcpy` and `std::bit_cast`. See also [What is the modern, correct way to do type punning in C++?](https://stackoverflow.com/q/67636231/11082165), [What is the strict aliasing rule?](https://stackoverflow.com/q/98650/11082165), [Unions and type-punning](https://stackoverflow.com/q/25664848/11082165), and other linked questions therein. – Brian61354270 Feb 09 '23 at 16:57
  • This question https://stackoverflow.com/questions/573294/when-to-use-reinterpret-cast is more general. I actually read in *The C++ Programming Language* by Bjarne Stroustrup that "reinterpret_cast handles conversions between unrelated types such as an integer to a pointer or a pointer to an unrelated pointer type" but I didn't get what was the use to convert an integer to a pointer. – Tesla123 Feb 09 '23 at 17:04
  • Some callback APIs will allow the registered callback to provide a parameter as a `void*`, which is passed to the call back when it is invoked. If the code that registers the callback has an `int` to use, it has to be cast to a `void*`, and then back from a `void*` to an `int`. – Eljay Feb 09 '23 at 17:06
  • @Brian `std::bit_cast` appeared with C++20 so many programmers can't use it. + I didn't know `std::memcpy` could be useful for type punning. I've always seen people use casts for type punning. – Tesla123 Feb 09 '23 at 17:10
  • *I've always seen people use casts for type punning.* Now you can tell those people they're doing it wrong, and explain why. – Eljay Feb 09 '23 at 18:47

0 Answers0