Boost logo

Boost :

From: Giovanni Piero Deretta (gpderetta_at_[hidden])
Date: 2008-04-19 11:31:20


On Fri, Apr 18, 2008 at 11:45 PM, Teemu Torma <teemu_at_[hidden]> wrote:
> On Friday 18 April 2008, Giovanni Piero Deretta wrote:
> > inline std::size_t float_hash_impl(float v)
> > {
> > std::size_t seed;
> > std::memcpy(&x, &v, sizeof(x));
> > return seed;
> > }
> >
> > should work and should produce optimal code, at least with a recent
> > gcc.
>
> Wouldn't casting using union be safe and efficient in all cases?
> Something like:
>
>
> inline std::size_t float_hash_impl(float v)
> {
> union { float v; std::size_t seed; } u;
> u.v = v;
> return u.seed;
> }
>

This is UB according to the standard, but it happens to works in most
compilers (gcc explicitly states that this is guaranteed to work),
but:

- memcpy produces already optimal code at least with gcc.
- gcc sometimes is more conservative with optimizations when it sees
an union (in fact I've seen gcc produce worse code with the union than
with the memcpy).

HTH,

-- 
gpd

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk