Error: copy assignment operator not allowed in union

依然范特西╮ 提交于 2020-01-14 09:38:20

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4049294/error-copy-assignment-operator-not-allowed-in-union

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!