Reinterpreting a union to a different union

后端 未结 4 937
时光说笑
时光说笑 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条回答
  •  梦毁少年i
    2021-02-01 15:43

    This is UB by omission. [expr.ref]/4.2:

    If E2 is a non-static data member and the type of E1 is “cq1 vq1 X”, and the type of E2 is “cq2 vq2 T”, the expression [E1.E2] designates the named member of the object designated by the first expression.

    During the evaluation of the given_b_or_c call in given_big, the object expression in little.h does not actually designate a Little object, and ergo there's no such member. Because the standard "omits any explicit definition of behavior" for this case, the behavior is undefined.

提交回复
热议问题