This is an strict aliasing question, as in will the compiler cause any optimization order problems with this.
Say that I have three public float
s in a struct XMFLOAT3
(not unlike this one.) And I want to cast to a float*
. Will this land me in optimization trouble?
XMFLOAT3 foo = {1.0f, 2.0f, 3.0f};
auto bar = &foo.x;
bar[2] += 5.0f;
foo.z += 5.0f;
cout << foo.z;
I assume this will always print "13". But what about this code:
XMFLOAT3 foo = {1.0f, 2.0f, 3.0f};
auto bar = reinterpret_cast<float*>(&foo);
bar[2] += 5.0f;
foo.z += 5.0f;
cout << foo.z;
I believe this is legal because, according to http://en.cppreference.com/w/cpp/language/reinterpret_cast#Type_aliasing
T2 is an aggregate type or a union type which holds one of the aforementioned types as an element or non-static member (including, recursively, elements of subaggregates and non-static data members of the contained unions): this makes it safe to cast from the first member of a struct and from an element of a union to the struct/union that contains it.
Is my understanding of this correct?
Obviously this will become implementation dependent on the declaration of XMFLOAT3
.