1

Assume I have

union myUnion
{
   short s;
   long l;
   char* cstr;
};

Now assume I get a pointer to a myUnion and know at compile type which "type" it is.

Is it save/correct to do this:

short s = *(static_cast<short*>(u)); // where u is a pointer to myUnion

I kinda think it is because if I understand unions in c++ correctly, for myUnion u

&u == &(u.s) == &(u.l) == &(u.cstr)

but I'm not sure and I fear that by doing this I get a ride to undefined behaviour land...

Thanks in advance for any input!

edit just to clarify: I know how to use a union "the normal way" (short s = u.s). I know that unions are there because of C and you probably don't want to use unions in moden c++ code.

I am asking because I am interested if the "static_cast" above is "bad".

1 Answers1

2

Unions are like structures, but all member variables share the same memory. That means to access a member you do it just like a normal structure.

In other words:

short s = u->s;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thank you. I know that. My question is if doing it the way described above is "ok". – omoithesane Dec 10 '14 at 11:58
  • @omoithesane You might want to read about [strict aliasing](http://stackoverflow.com/q/98650/440558). What you're doing is violating the strict aliasing rule and that can lead to bad things. – Some programmer dude Dec 10 '14 at 12:00
  • ok, so the static_cast is undefined behaviour because it aliases a union as, f.ex., a short. So how about this: memcpy(&aShort, &u, sizeof(short))? – omoithesane Dec 10 '14 at 12:18
  • @omoithesane The `memcpy` call should work fine, as would e.g. `std::copy`. I just don't see the reason for it ([recommended reading about the XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)). – Some programmer dude Dec 10 '14 at 12:35
  • I neither have a problem nor is the above or the memcpy approach a solution ;) I was just curious if it would work. Thanks for help :) – omoithesane Dec 10 '14 at 12:49