zoukankan      html  css  js  c++  java
  • when to use reinterpret_cast

    写的太好了。。

    When you convert for example int(12) to unsigned float (12.0f) your processor needs to invoke some calculations as both numbers has different bit representation. This is what static_cast stands for.

    On the other hand, when you call reinterpret_cast the CPU does not invoke any calculations. It just treats a set of bits in the memory like if it had another type. So when you convert int* to float* with this keyword, the new value (after pointer dereferecing) has nothing to do with the old value in mathematical meaning.

    Example: It is true that reinterpret_cast is not portable because of one reason - byte order (endianness). But this is often surprisingly the best reason to use it. Let's imagine the example: you have to read binary 32bit number from file, and you know it is big endian. Your code has to be generic and works properly on big endian (e.g. ARM) and little endian (e.g. x86) systems. So you have to check the byte order. It is well-known on compile time so you can write constexpr function:

    constexpr bool is_little_endian() {
      std::uint16_t x=0x0001;
      auto p = reinterpret_cast<std::uint8_t*>(&x);
      return *p != 0;
    }

    Explanation: the binary representation of x in memory could be 0000'0000'0000'0001 (big) or 0000'0001'0000'0000 (little endian). After reinterpret-casting the byte under p pointer could be respectively 0000'0000 or 0000'0001. If you use static-casting, it will always be 0000'0001, no matter what endianness is being used.

  • 相关阅读:
    错误: error C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. 的处理方法
    C语言习题
    嵌入式芯片STM32F407
    c语言课后习题
    求方程式的根
    C语言课后习题
    LINUX常用指令
    在 pythonanywhere 上搭建 django 程序(Virtualenv+python2.7+django1.8)
    Git远程操作详解
    ./configure,make,make install的作用
  • 原文地址:https://www.cnblogs.com/likemao/p/10117959.html
Copyright © 2011-2022 走看看