When to use reinterpret_cast?

前端 未结 11 1210
我寻月下人不归
我寻月下人不归 2020-11-22 08:41

I am little confused with the applicability of reinterpret_cast vs static_cast. From what I have read the general rules are to use static cast when

11条回答
  •  孤街浪徒
    2020-11-22 09:37

    First you have some data in a specific type like int here:

    int x = 0x7fffffff://==nan in binary representation
    

    Then you want to access the same variable as an other type like float: You can decide between

    float y = reinterpret_cast(x);
    
    //this could only be used in cpp, looks like a function with template-parameters
    

    or

    float y = *(float*)&(x);
    
    //this could be used in c and cpp
    

    BRIEF: it means that the same memory is used as a different type. So you could convert binary representations of floats as int type like above to floats. 0x80000000 is -0 for example (the mantissa and exponent are null but the sign, the msb, is one. This also works for doubles and long doubles.

    OPTIMIZE: I think reinterpret_cast would be optimized in many compilers, while the c-casting is made by pointerarithmetic (the value must be copied to the memory, cause pointers couldn't point to cpu- registers).

    NOTE: In both cases you should save the casted value in a variable before cast! This macro could help:

    #define asvar(x) ({decltype(x) __tmp__ = (x); __tmp__; })
    

提交回复
热议问题