2

I have this structure which I've been using without bugs so far:

union Vector3f
{
  struct{ float x,y,z ; } ;
  float elts[3];
} ;

There are a couple of overloaded constructors, but I left the copy constructor and assignment operator= to their default implementations.

Vector3f a,b ;
b=a; //works as expected, with x,y,z copied over from a to b

It just occurred to me that default memberwise assignment should execute b.elts=a.elts, which since elts is a pointer type, should result in b.elts incorrectly pointing to a.elts.

However, explicitly attempting b.elts=a.elts fails with compilation error

Array type float[3] is not assignable

Is this something to worry about? Is my code ok or should I explicitly write a copy ctor and assignment operator=?

timrau
  • 22,578
  • 4
  • 51
  • 64
bobobobo
  • 64,917
  • 62
  • 258
  • 363
  • 4
    In title you mentioned `struct`, but in the body you wrote `union`. Which is your actual question? – timrau Aug 29 '13 at 17:42
  • 7
    `elts` is not a pointer type. – Benjamin Lindley Aug 29 '13 at 17:45
  • 2
    Don't use a union this way. It's undefined behavior to read from a union member that hasn't been assigned to directly, so you get little use from this representation. The trick may technically work, but it's always a bit ugly and unstable. Use a regular class with `operator[]` or `x()`, `y()` and `z()`. – GManNickG Aug 29 '13 at 17:49
  • Note that an array of 3 elements is not required to have the same layout as three distinct elements. – Pete Becker Aug 29 '13 at 18:19
  • @PeteBecker Yes, I've heard [this argument before](http://stackoverflow.com/a/2313676/111307), it's basically a misconception (see comment thread below answer). – bobobobo Aug 29 '13 at 21:11
  • @bobobobo - please point to the requirement in the standard that `float elts[3]` and `float f; float g; float h;` must have the same layout. – Pete Becker Aug 30 '13 at 12:48
  • Those floats are declared inside an anonymous struct. `struct { float f,g,h; };` will be stored contiguously and in order (assuming the compiler does not insert any padding). [Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so that later members have higher addresses within a class object.](http://stackoverflow.com/a/11340165/111307) – bobobobo Aug 30 '13 at 14:50

0 Answers0