Re: assignment operators for union member classes

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 2/19/08, Mike Welsen <mikewelsen@xxxxxxxxxxx> wrote:
> Does anyone know why asignment operators are not allowed for
> union class members?

The compiler needs to synthesize an assignment operator for the
union itself, but since the union's active field is not known, the
compiler cannot know which field to copy when copying the union.
So the compiler cannot do any better than copying all fields
simultaneously, which means using something like memcpy.  And so,
the C++98 standard makes using type with non-trivial assignment
operators illegal as union members.

> Other compilers accept this code, but I can't compile the following
> code with GCC.

Those other compilers are in error.

> (error: member 'A C::::::aa' with copy assignment operator
> not allowed in union)
>
> class A {
>   public:
>    int a;
>    A& operator=(const A&){return (*this);}
>    int AFunc(void){}
> };
>
> class B{
>   public:
>    int b;
> };
>
> class C {
>   public:
>    C(){}
>    union {
>      struct {A aa;}; // builds with warning if level4 is set
>      B bb;
>    };
> };

The C++0x standard will add a new feature that allows you to have
non-trivial assignment operators for union fields.  The catch is
that you will have to explictly code the surrounding assignment
operator, the compiler cannot figure it out.

-- 
Lawrence Crowl

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux