From e563066c7602b5a93f62b2bd55335acd2ee7e2f4 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Sat, 19 Sep 2015 03:25:57 +0200 Subject: [PATCH] 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. --- include/wx/any.h | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/include/wx/any.h b/include/wx/any.h index f75db97559..8490555be3 100644 --- a/include/wx/any.h +++ b/include/wx/any.h @@ -192,11 +192,7 @@ class wxAnyValueTypeOpsInplace public: static void DeleteValue(wxAnyValueBuffer& buf) { - T* value = reinterpret_cast(&buf.m_buffer[0]); - value->~T(); - - // Some compiler may given 'unused variable' warnings without this - wxUnusedVar(value); + GetValue(buf).~T(); } static void SetValue(const T& value, @@ -209,11 +205,17 @@ public: static const T& GetValue(const wxAnyValueBuffer& buf) { - // Breaking this code into two lines should suppress - // GCC's 'type-punned pointer will break strict-aliasing rules' - // warning. - const T* value = reinterpret_cast(&buf.m_buffer[0]); - return *value; + // Use a union to avoid undefined behaviour (and gcc -Wstrict-alias + // warnings about it) which would occur if we just casted a wxByte + // pointer to a T one. + union + { + const T* ptr; + const wxByte *buf; + } u; + u.buf = buf.m_buffer; + + return *u.ptr; } };