Safe and efficient Punning type in C ++

uint32_t Seed() {
    uint64_t seed = GetSomeReasonable64BitIntegerSeed();
    return *(uint32_t*)&seed ^ *((uint32_t*)&seed + 1);
}

      

Above is not real code, but basically what real code does. I got a warning from g ++ that it violates strict alias, post it to google and I want to fix it. I found this question, but it does not provide a clear solution, other than using memcpy

, or relying on undefined, but with little or no problem, is accessing an unidentified union member.

The current options that I can think of are

  • Use memcpy

    .
  • Use union

    and compile this part as C, where the standard language allows types to be injected through unions.
+3


source to share


1 answer


Bit arithmetic is well defined and arguably more efficient. In this example:



return seed ^ (seed >> 32);

      

+8


source







All Articles