5

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]’
user2023370
  • 10,488
  • 6
  • 50
  • 83

3 Answers3

3

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).

sam hocevar
  • 11,853
  • 5
  • 49
  • 68
0

Yes. Its possible but you've to initialized it when its constructed. You cannot leave it uninitialized. But in this particular case, I don't think its possible, since you cannot initialize an array in the initialization-list.

By the way, have a look at this interesting topic:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

No. Try using GCC's -pedantic switch:

  warning: ISO C++ prohibits anonymous structs

The example is therefore also illegal with the consts removed.

user2023370
  • 10,488
  • 6
  • 50
  • 83
  • I am afraid this does not answer the question. Anonymous structs are forbidden, but not anonymous unions. – sam hocevar Mar 06 '12 at 13:59
  • @SamHocevar Thankyou! I appreciate your contribution, but surely the answer is technically still no: I was looking for legal C++. – user2023370 Mar 06 '12 at 21:21
  • Maybe you could edit the question, then? It states _“Is it possible to have an anonymous union with const members“_ to which the answer appears to be yes. You seem to have a different problem with anonymous `struct`s. – sam hocevar Mar 06 '12 at 21:37