Re: is portable aliasing possible in C++?

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

 



On 4 September 2014 17:51, Andrew Haley wrote:
> The "union trick" has always worked with GCC, and is now hallowed by
> the standard.  It's also easy to understand.  It generates code as
> efficient as all the other ways of doing it, AFAIAA.  It's what we
> have always recommended.

Type punning with unions is allowed in C since C99 but not by any C++
standard (although it does work with GCC).

Placement new might work with GCC in practice as long as the buffer is
correctly aligned and the type being constructed does not have
non-trivial initialization. However, my reading of the standard is
that after the placement new, if the object's members are not
initialized then they have indeterminate values (not the values that
were at those memory addresses already, even though that's likely to
be what happens in practice). Objects with indeterminate values can
only be used in very limited ways and generally lead to undefined
behaviour, and code with undefined behaviour does not usually mix well
with aggressive optimizations.

FWIW I prefer the memcpy approach, it usually generates the same code
as type punning via a union, but is more portable and has guaranteed
results that are well-defined (and if you're interested in maximum
performance then you should not be using unoptimized code, so it
shouldn't matter that the mempcy solution relies on optimizations).




[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