An union with a const and a nonconst member?

后端 未结 3 1203
伪装坚强ぢ
伪装坚强ぢ 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:11

    If it's any consolation - the Microsoft Xbox 360 compiler (which is based on Visual Studio's compiler) does error out. Which is funny, because that's usually the most lenient of the bunch.

    error C2220: warning treated as error - no 'object' file generated
    warning C4510: 'A' : default constructor could not be generated
        : see declaration of 'A'
    warning C4610: union 'A' can never be instantiated - user defined constructor required
    

    This error goes away if I take the const away. gcc-based compilers don't complain.

    EDIT: The Microsoft Visual C++ compiler has the same warning.

提交回复
热议问题