Accessing same-type inactive member in unions

后端 未结 1 2036
别跟我提以往
别跟我提以往 2020-12-06 01:01

I have something like this:

union DataXYZ
{
    struct complex_t
    {
        float real, imag;
    } complex;

    struct vector_t
    {
        float magn         


        
相关标签:
1条回答
  • 2020-12-06 01:42

    Yes you can read the other member in this particular case.

    This is what the C++11/14 standard has to say:

    9.5 - Unions

    In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.

    But the note immediately after the section makes your particular instance legal since one special guarantee is made in order to simplify the use of unions:

    [ Note: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. —end note ]

    And your structs do share a common initial sequence:

    9.2.16 - Class members

    The common initial sequence of two standard-layout struct (Clause 9) types is the longest sequence of non- static data members and bit-fields in declaration order, starting with the first such entity in each of the structs, such that corresponding entities have layout-compatible types and either neither entity is a bit-field or both are bit-fields with the same width.

    0 讨论(0)
提交回复
热议问题