is portable aliasing possible in C++?

haynberg@yahoo.com haynberg@yahoo.com
Tue Sep 9 23:13:00 GMT 2014


Using reinterpret_cast to convert between unrelated pointer types is a language feature that, by definition, makes your code not portable (assuming you dereference).

While it's undefined by the standard, that doesn't mean it's undefined for a given platform (OS/compiler/compiler options).  For example, on an architecture which allows unaligned reads and the compiler does not perform strict-aliasing optimizations, it's likely OK (e.g. MS or Clang on x86).  If the compiler does perform those optimizations and provides a way to programmatically disable them (like GCC's may_alias) and you make use of that feature correctly, it's also likely OK.  But if the compiler does perform those optimizations and it doesn't provide something like may_alias, then it is undefined, and you have no choice but to disable the optimization for the whole program or resort to memcpy.

So it would seem the answer is no, portable aliasing is not possible in C++.  Though I wonder if it should be (with a new language feature).

Jay Haynberg



More information about the Gcc-help mailing list