What happened to the “aggregate or union type that includes one of the aforementioned types” strict aliasing rule?

The lvalue you use to access the stored value of y is not *reinterpret_cast<Foo*>(&y), of type Foo, but it is reinterpret_cast<Foo*>(&y)->x, which has the type float. Accessing a float using an lvalue of type float is fine. In C++, you can not “access the value of a union or struct” (as whole), you can only access individual members. The rationale you quoted points to a difference between C and C++:

  struct X { int a, b; };
  struct X v1 = {1, 2}, v2;
  v2 = v1;

In C, the standard says that the assignment loads the value of v1 (as whole) to assign it to v2. Here the values of the objects v1.a and v2.b (both have types int) are accessed using an lvalue of type struct X (which is not int).

In C++, the standard says that the assignment calls the compiler generated assignment operator which is equivalent to

struct X {
   ...
   struct X& operator=(const struct X&other)
   {
       a = other.a;
       b = other.b;
   }
};

In this case, calling the assignment operator does not access any value, because the RHS is passed by reference. And executing the assignment operator accesses the two int fields separately (which is fine, even without the aggregate rule), so this is again not accessing a value through an lvalue of type struct X.

Leave a Comment