tags:

views:

22

answers:

2

I am compiling the code below when the following erro comes up. I am unable to find the reason.

typedef union  {
   struct {
     const  int j;
   } tag;
} X;


int main(){
    return 0;
}
error: member `<`anonymous union>::`<`anonymous struct> `<`anonymous union>::tag with copy assignment operator not allowed in union

This code compiles fines with gcc though. Gives error only with g++.

+3  A: 

In order to have a member of a union of some class type T, T's special member functions (the default constructor, copy constructor, copy assignment operator, and destructor) must be trivial. That is, they must be the ones implicitly declared and defined by the compiler.

Your unnamed struct does not have a trivial copy assignment operator (in fact, it doesn't have one at all) because it has a member variable that is const-qualified, which suppresses generation of the implicitly declared copy assignment operator.

James McNellis
+1  A: 

The compiler tries to generate an assignment operator for the union itself, and fails because the active field of the union if not known, so it falls back to a bit-for-bit copy of the object. However, it can't do that either, since struct { const int j; } has a non-trivial assignment operator.

See http://gcc.gnu.org/ml/gcc-help/2008-03/msg00051.html.

Frédéric Hamidi