c++ difference between reinterpret cast and c style cast

后端 未结 4 671
南旧
南旧 2021-02-10 17:19

Code:

char keyStr[50]={ 0x5F, 0x80 /* bla bla */ };
uint32_t* reCast  = reinterpret_cast< uint32_t* >( &keyStr[29] );
uint32_t* reCast2 = ( uint32_t* )         


        
4条回答
  •  醉话见心
    2021-02-10 17:51

    In your example there are no differences between the C style cast and the reinterpret_cast, because you are casting between unrelated pointers, and there is no constness. If you have had a const on one part, reinterpret_cast would have choked when C style cast would have done the const_cast under the hood.

    The danger of the reinterpret_cast (or of the C style cast) is precisely that it allows casting between unrelated objects. In your example, you have a high risk that when you dereference reCast (or reCast2) you get an error because you try to access a misaligned integer.

    At low level, all casting have same effect (if they are valid) : they will all give the value or address. The main difference is :

    • a C style cast will (almost) always be allowed at compile time - I do not know examples where it will give a compile error but it might be compiler dependant
    • a reinterpret_cast will be allowed in same cases provided there is no constness change
    • a const_cast can only change constness
    • a static_cast will only be allowed (at compile time) between related types

    All this cast were added in C++ to avoid the catch all mode of C style cast and allow for some compile and run time checks. - a dynamic_cast will only be allowed at compile time between related types and the compiler will insert code to control validity at run time

提交回复
热议问题