This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: is portable aliasing possible in C++?
- From: haynberg at yahoo dot com
- To: Andrew Haley <aph at redhat dot com>, "gcc-help at gcc dot gnu dot org" <gcc-help at gcc dot gnu dot org>
- Date: Thu, 11 Sep 2014 16:25:38 -0700
- Subject: Re: is portable aliasing possible in C++?
- Authentication-results: sourceware.org; auth=none
- References: <1410390231 dot 39617 dot YahooMailNeo at web140202 dot mail dot bf1 dot yahoo dot com> <54115917 dot 1040602 at redhat dot com>
- Reply-to: haynberg at yahoo dot com
>> msg *p = reinterpret_cast<msg*>(get_bytes());
>
> Why are you doing this?
For efficiency, by preventing a copy (imagine get_bytes() is getting bytes out of a socket buffer).
Putting alignment/padding concerns aside, it would be nice if there was a way to explicitly tell the compiler, I want to do this and, please donât reorder stores and loads, or perform other strict-aliasing optimizations, on the memory pointed to by this pointer (similar to the effect of a memcpy). I believe the only way to do this is with the GCC may_alias attribute, or a more heavy-handed memory clobber. I think the OP wanted to ask the GCC folks if there was another, possibly more portable, way; for example, placement new, but that turned out not to be an option.
Another related, maybe more important, question is if GCC sees a reinterpet_cast like this (without a may_alias type), is it free to discard code or otherwise drastically change it due to the fact that itâs undefined by the standard? Like some of the cases shown in:
âany undefined behavior in C gives license to the implementation (the compiler and runtime) to produce code that ... does completely unexpected things, or worseâ
http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html
Jay Haynberg