How to use reinterpret_cast in C++?

后端 未结 5 505
无人及你
无人及你 2021-01-01 16:18

I know the reinterpret_cast in C++ can be used in this way:

float a = 0;
int b = *reinterpret_cast(&a);

Bu

5条回答
  •  一向
    一向 (楼主)
    2021-01-01 16:29

    why cannot cast it directly?

    I believe that this is a pure design decision, to make C++ more type-safe than C.

    reinterpret_cast is very dangerous, because it can involve type aliasing which is a short way to undefined behavior. When you use C++ casts, you sign a contract with your compiler "I know, what I am doing". So, all these long operators names, angle brackets, type-pointer-type conversions telling you: "Wait, don't do it. Maybe there is something wrong in your code design!".

    Also, not all C++ compilers allow type aliasing (either achieved by casting or by unions).

提交回复
热议问题