search

Home  >  Q&A  >  body text

C++不同指针直接互相转换用static cast还是reinterpret cast?

如题, 不同类型的指针应该算是相同的吗?
因为本质上都是地址, 那么按理来说应该是static cast, 但是由于指针类型不同好像又是应该用reinterpret cast,所以这种情况下该用哪种类型转换呢?

PHPzPHPz2803 days ago567

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:25:45

    Use reinterpret_cast with caution, because the purpose of this thing is to fool the compiler. Its conversion only changes the interpretation method, but does not change the actual data. If t的类型是TYPE, then x=reinterpret_cast<>(t)Equivalent to *((TYPE*)(&x))=t, if you use reinterpret_cast to convert an int to a float, it just copies the binary data completely, and the result is meaningless... Of course, to take a step back , of course you can use reinterpret_cast to achieve the pointer conversion you want

    and static_cast will check the type, so it can be used for conversion of built-in types (for example, from int to float, it can be converted according to semantics), but if it is for pointers, they must be types on the same inheritance tree to be able to communicate with each other. Conversion, and only upcasting (from subclass to base class) is guaranteed to be safe.

    Since your char* has no inheritance relationship with the target pointer, then obviously you can only use reinterpret_cast or C风格强转

    The questioner is struggling with the memory pool recently...

    reply
    0
  • 阿神

    阿神2017-04-17 14:25:45

    reinterpret_cast It is just a reinterpretation and does not actually involve address transformation. There is no problem when converting ordinary pointers, but when converting between parent and child class pointers, the result may be incorrect.

    reply
    0
  • Cancelreply