This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: How to use __attribute__((__may_alias__))
John Fine wrote:
> I have a working version, using a union in a way that I think is
> incorrect, but this is the same concept I used last time I fixed one of
> these issues.
>
> Everything I've tried so far with __attribute__((__may_alias__)) has
> failed. I'd really like to know how to make that work.
>
> Working code:
>
> union { DAT* pp; std::size_t dummy; } no_strict_alias;
> no_strict_alias.pp =foo();
> reinterpret_cast<DAT_PTR*>(&no_strict_alias.pp)->bar(x);
>
> Notice that dummy is never used. Notice that the reinterpret_cast is
> essentially unchanged (from the version that doesn't work). The union
> is just doing what I would have expected the attribute to do, marking
> pp as an object for which strict aliasing optimizations should not be
> used.
No, this isn't guaranteed to work. Your data must be *declared* as
union no_strict_alias. Casting to a pointer to union no_strict_alias
isn't the same unless the only way you ever access your data is via
that cast.
Andrew.