How to use __attribute__((__may_alias__))
Ian Lance Taylor
iant@google.com
Wed Mar 18 15:37:00 GMT 2009
John Fine <johnsfine@verizon.net> writes:
> Ian Lance Taylor wrote:
>> When you can't use a union, another option is memcpy.
>>
> That's a pretty ugly choice.
It's not so bad in C++. Something like this:
template <class dest, class source>
inline dest bit_cast(const source& s) {
// Compile time assertion: sizeof(dest) == sizeof(source)
typedef char assertion[sizeof(dest) == sizeof(source) ? 1 : -1];
dest d;
memcpy(&d, &s, sizeof(dest));
return d;
}
lets you write bit_cast<type>(value) and uses memcpy to avoid any
aliasing issues. While the memcpy looks bad, in practice the compiler
can normally eliminate it.
> I tried that, even though it makes no sense to me (it protects the
> wrong level of indirection). It didn't work.
I have most likely misunderstood which level you needed to may_alias.
The point was simply to use a typedef to set may_alias. The may_alias
attribute should apply to the type to which you are pointing, not the
pointer.
Ian
More information about the Gcc-help
mailing list