An union with a const and a nonconst member?

后端 未结 3 1226
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 12:40

This appears to be undefined behavior

union A {
  int const x;
  float y;
};

A a = { 0 };
a.y = 1;

The spec says

Cr

3条回答
  •  旧巷少年郎
    2021-01-01 13:15

    The latest C++0x draft standard is explicit about this:

    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.

    So your statement

    a.y = 1;
    

    is fine, because it changes the active member from x to y. If you subsequently referenced a.x as an rvalue, the behaviour would be undefined:

    cout << a.x << endl ; // Undefined!
    

    Your quote from the spec is not relevant here, because you are not creating any new object.

提交回复
热议问题