Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: copy assignment operator not allowed in union

Tags:

c++

struct

unions

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

like image 386
deeJ Avatar asked Oct 29 '10 05:10

deeJ


2 Answers

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.

like image 70
James McNellis Avatar answered Nov 12 '22 18:11

James McNellis


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.

like image 24
Frédéric Hamidi Avatar answered Nov 12 '22 17:11

Frédéric Hamidi