Reinterpret_cast vs. C-style cast

前端 未结 6 1595
谎友^
谎友^ 2020-12-01 03:06

I hear that reinterpret_cast is implementation defined, but I don\'t know what this really means. Can you provide an example of how it can go wrong, and it goes

6条回答
  •  离开以前
    2020-12-01 03:13

    There are valid reasons to use reinterpret_cast, and for these reasons the standard actually defines what happens.

    The first is to use opaque pointer types, either for a library API or just to store a variety of pointers in a single array (obviously along with their type). You are allowed to convert a pointer to a suitably sized integer and then back to a pointer and it will be the exact same pointer. For example:

    T b;
    intptr_t a = reinterpret_cast( &b );
    T * c = reinterpret_cast(a);
    

    In this code c is guaranteed to point to the object b as you'd expected. Conversion back to a different pointer type is of course undefined (sort of).

    Similar conversions are allowed for function pointers and member function pointers, but in the latter case you can cast to/from another member function pointer simply to have a variable that is big enouhg.

    The second case is for using standard layout types. This is something that was de factor supported prior to C++11 and has now been specified in the standard. In this case the standard treats reinterpret_cast as a static_cast to void* first and then a static_cast to the desination type. This is used a lot when doing binary protocols where data structures often have the same header information and allows you to convert types which have the same layout, but differ in C++ class structure.

    In both of these cases you should use the explicit reinterpret_cast operator rather than the C-Style. Though the C-style would normally do the same thing, it has the danger of being subjected to overloaded conversion operators.

提交回复
热议问题