Accessing inactive union member and undefined behavior?

前端 未结 5 1299
独厮守ぢ
独厮守ぢ 2020-11-21 06:00

I was under the impression that accessing a union member other than the last one set is UB, but I can\'t seem to find a solid reference (other than answers clai

5条回答
  •  悲&欢浪女
    2020-11-21 06:40

    I think the closest the standard comes to saying it's undefined behavior is where it defines the behavior for a union containing a common initial sequence (C99, §6.5.2.3/5):

    One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the complete type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

    C++11 gives similar requirements/permission at §9.2/19:

    If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

    Though neither states it directly, these both carry a strong implication that "inspecting" (reading) a member is "permitted" only if 1) it is (part of) the member most recently written, or 2) is part of a common initial sequence.

    That's not a direct statement that doing otherwise is undefined behavior, but it's the closest of which I'm aware.

提交回复
热议问题