Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor and anonymous union with const members

Is it possible to have an anonymous union with const members? I have the following:

struct Bar {
  union {
    struct { const int x, y; };
    const int xy[2];
  };
  Bar() : x(1), y(2) {}
};

With G++ 4.5 I get the error:

error: uninitialized member ‘Bar::<anonymous union>::xy’ with ‘const’ type ‘const int [2]’
like image 979
user2023370 Avatar asked Oct 25 '22 07:10

user2023370


1 Answers

This was a problem in GCC that was fixed in version 4.6. Your code now works fine.

It still depends on a GCC extension because it uses an anonymous struct, but most compilers support them now. Also, the following code now builds properly with -pedantic:

struct Bar {
  union {
    const int x;
    const int y;
  };
  Bar() : x(1) {}
};

That code is also accepted by Clang and Visual Studio 2010 (but fails with 2008).

like image 110
sam hocevar Avatar answered Oct 26 '22 23:10

sam hocevar