Avoid gcc -Wstrict-alias=2 warnings in wxAny

While wxWidgets itself is compiled with -fno-strict-aliasing, the user code
including wx headers can be compiled without it and, worse, even with
-Wstrict-aliasing=2 which would give tons of warnings (two for each
instantiation of the template class) of possibly breaking strict aliasing rule.

Fix this by using a union to cast between two pointers of different types
instead of using a reinterpret cast.
This commit is contained in:
Vadim Zeitlin
2015-09-19 03:25:57 +02:00
parent e5fe3977f4
commit e563066c76

View File

@@ -192,11 +192,7 @@ class wxAnyValueTypeOpsInplace
public: public:
static void DeleteValue(wxAnyValueBuffer& buf) static void DeleteValue(wxAnyValueBuffer& buf)
{ {
T* value = reinterpret_cast<T*>(&buf.m_buffer[0]); GetValue(buf).~T();
value->~T();
// Some compiler may given 'unused variable' warnings without this
wxUnusedVar(value);
} }
static void SetValue(const T& value, static void SetValue(const T& value,
@@ -209,11 +205,17 @@ public:
static const T& GetValue(const wxAnyValueBuffer& buf) static const T& GetValue(const wxAnyValueBuffer& buf)
{ {
// Breaking this code into two lines should suppress // Use a union to avoid undefined behaviour (and gcc -Wstrict-alias
// GCC's 'type-punned pointer will break strict-aliasing rules' // warnings about it) which would occur if we just casted a wxByte
// warning. // pointer to a T one.
const T* value = reinterpret_cast<const T*>(&buf.m_buffer[0]); union
return *value; {
const T* ptr;
const wxByte *buf;
} u;
u.buf = buf.m_buffer;
return *u.ptr;
} }
}; };