This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: assignment operators for union member classes
- From: "Lawrence Crowl" <crowl at google dot com>
- To: "Mike Welsen" <mikewelsen at hotmail dot com>
- Cc: "GCC -Help" <gcc-help at gcc dot gnu dot org>
- Date: Thu, 6 Mar 2008 14:57:37 -0800
- Subject: Re: assignment operators for union member classes
- References: <BLU133-W1067A101791A39DF6403C0C3220@phx.gbl>
On 2/19/08, Mike Welsen <mikewelsen@hotmail.com> 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