mojmir svoboda wrote: > the time has come and i am resolving these strict aliasing issues > in our project i mentioned about a year ago. > > few questions popped up: > > Q1: what is the difference between > W1: dereferencing type-punned pointer will break... > and > W2: dereferencing type-punned pointer might break...? > > i'm getting the W1 version in constructs like: > C_VertexPosCompression > { > Vector3 m_Offset; > float m_Scale; > const Vector4 & GetOffsetAndScale() const > { return *(const Vector4*) &m_Offset; } > }; > > i'm getting the W2 version in constructs like: > class Vector3 > { > float x, y, z; > const Vector2 & GetVector2 () const { return *(const Vector2*)&x; } > }; > > but i do not see any difference between them. enlighten me, please :) I'm not sure. It doesn't much matter, as the code is wrong in both cases. I don't know what type a Vector2 is. > Q2: this is excerpt from noname commercial software. i'd like to know > whether the cast through pointer-to-union is valid solution and whether > the note in the comment is really true. No, it isn't really true. Casting through a pointer to union doesn't work. All it does is shut up the compiler, and I'm glad to see that -Wstrict-aliasing=2 still works despite this. > Q3: i know already that following solution is common > > template<class Tgt, class Src> TargetT type_pun (Src & s) { > union convert { Src src; Tgt tgt; } conv; > conv.src = s; return conv.tgt; > } > > so i would resolve Q2 this way: > float separation = type_pun<float>(binary); > is it better than the original u32f32 * cast? Yes. Much. > Q4: will this version do the same as in Q3? > > template<class Tgt, class Src> Tgt & type_pun (Src & s) > { > union convert { Src * src; Tgt * tgt; } conv; > conv.src = &s; return *conv.tgt; > } No. What matters is the type of the object, not the type of the pointer. > Q5: when i fix for example the > C_VertexPosCompression > { > Vector3 m_Offset; float m_Scale; > Vector4 GetOffsetAndScale() const > { return C_Vector4(m_Offset, m_Scale); } > }; > is there a chance that the temporary will be eventually optimized out? I think so, but this isn't a full example. You can easily check. Andrew.