Reinterpreting a union to a different union

后端 未结 4 949
时光说笑
时光说笑 2021-02-01 15:16

I have a standard-layout union that has a whole bunch of types in it:

union Big {
    Hdr h;

    A a;
    B b;
    C c;
    D d;
    E e;
    F f;
};

4条回答
  •  鱼传尺愫
    2021-02-01 15:43

    I'm not sure, if this really applies here. In the reinterpret_cast - Notes section they talk about pointer-interconvertible objects.

    And from [basic.compound]/4:

    Two objects a and b are pointer-interconvertible if:

    • they are the same object, or
    • one is a union object and the other is a non-static data member of that object, or
    • one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, the first base class subobject of that object, or
    • there exists an object c such that a and c are pointer-interconvertible, and c and b are pointer-interconvertible.

    If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_­cast.

    In this case, we have Hdr h; (c) as a non-static data member in both unions, which should allow to (because of the second and last bullet point)

    Big* (a) -> Hdr* (c) -> Little* (b)
    

提交回复
热议问题