This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
strict aliasing questions
- From: mojmir svoboda <mojmir dot svoboda at 2kczech dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Fri, 2 Oct 2009 10:13:06 +0200
- Subject: strict aliasing questions
good morning guys,
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 :)
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.
typedef unsigned u32;
typedef float f32;
#define SIGN_BITMASK 0x80000000
union u32f32 {
u32 u;
f32 f;
};
int main ()
{
unsigned array[1024]; unsigned const * stream = &array[0];
u32 binary = *stream++;
u32 is32bits = binary & SIGN_BITMASK;
binary |= SIGN_BITMASK;
/* To avoid strict-aliasing warnings on gcc, unions are used to read
from the stream.
Note: You will still get a warning if gcc -Wstrict-aliasing=2 is used
but this is a false positive.
*/
u32f32 * sep = reinterpret_cast<u32f32 *>(&binary);
float separation = sep->f;
}
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?
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;
}
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?
many thanks for your attention,
mojmir