Re: How to use __attribute__((__may_alias__))

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



John Fine <johnsfine@xxxxxxxxxxx> 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

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux