在 2018-08-10 06:20, Kim Gräsman 写道:
On Fri, Aug 10, 2018 at 12:02 AM, Jonathan Wakely <jwakely....@gmail.com>
wrote:

If GCC 4.9.3 thinks there's an aliasing violation it might
misoptimise. It doesn't matter if it's right or not, it matters if it
treats the code as undefined or not.

And apparently GCC does think there's a violation, because it warns.

Unless you're sure that not only is the code OK, but GCC is just being
noisy and doesn't misoptimise, then I think using -fno-strict-aliasing
is safer than just suppressing the warning.

Good point, I can see how that would play out nicer.

So this would probably need to be addressed in the LLVM build system, I'll
try and work up a patch tomorrow.


When I used to do such type punning in C, I got similar warnings. Then I looked for some solutions... I can't recall the principle now and I fail to find it in the C or C++ standard. Despite that, the solution is simple:

Only an lvalue of a pointer to (possibly CV-qualified) `void` or a pointer to a character type (in C) / any of `char`, `unsigned char` or `std::byte` (in C++) can alias objects.

That is to say, in order to eliminate the aliasing problem an intermediate lvalue pointer is required.

Hence, altering
```
    return *reinterpret_cast<T *>(Union.buffer);
```
to
```
    auto p = static_cast<void *>(Union.buffer);
    return *static_cast<T *>(p);
```
will probably resolve this problem.


Thanks,
- Kim



--
Best regards,
LH_Mouse

Reply via email to