C++ When should we prefer to use a two chained static_cast over reinterpret_cast

前端 未结 6 1533
不思量自难忘°
不思量自难忘° 2020-12-04 01:29

First of all, this is not a duplicate of Why do we have reinterpret_cast in C++ when two chained static_cast can do it\'s job?.

I know situations where we cannot use

6条回答
  •  隐瞒了意图╮
    2020-12-04 02:13

    reinterpret_cast should be a huge flashing symbol that says THIS LOOKS CRAZY BUT I KNOW WHAT I'M DOING. Don't use it just out of laziness.

    reinterpret_cast means "treat these bits as ..." Chained static casts are not the same because they may modify their targets according to the inheritence lattice.

    struct A {
        int x;
    };
    
    struct B {
        int y;
    };
    
    struct C : A, B {
        int z;
    };
    
    C c;
    A * a = &c;
    
    int main () {
        assert (reinterpret_cast  (a) != static_cast  (static_cast  (a)));
    }
    

    If you are not 100% sure that a points to a b, use dynamic_cast which will search for the above solution (albeit with a runtime cost). Bear in mind that this may return NULL or throw on failure.

    I'm trying to think of times when I've actually used reinterpret_cast, there are really only two:

    • when a function is zipping/encrypting an arbitrary buffer and I want to use a const char * to traverse it
    • if(*reinterpret_cast(array_of_4_bytes_A) < *reinterpret_cast(array_of_4_bytes_B) or somesuch. Lines like this invite scrutiny and demand comments.

    Otherwise if you have a A* which is really a B* then you probably want a union.

提交回复
热议问题