3 ms·
> Punning through a union is undefined in C++11 And that is effectively a bug in that standard, says Linus, and I agree with him. https://lkml.org/lkml/2018/6
by acqq 8y ago
> Punning through a union is undefined in C++11
And that is effectively a bug in that standard, says Linus, and I agree with him.
https://lkml.org/lkml/2018/6/5/769 https://lkml.org/lkml/2018/6/5/769
"I've said this before, and I'll say it again: a standards paper is
just so much toilet paper when it conflicts with reality."
Sadly, the compiler maintainers at some points of time managed to push the real "breaking" changes through (for other UB cases). It seems that the "language lawyerism" is "easier" than the expected approach of the responsible engineers.
- saagarjha 8y agoI disagree with Linus here. If you're going to go through a complicated set of hoops to make punning work (namely, doing it through a union), what's so hard about using the intended (memcpy) solution? Like, if you really think the standard is that terrible (which isn't what I'm arguing here–I haven't personally made up an opinion on this yet), why not just straight cast and force GCC to adopt a flag that makes your behavior legal?
- AstralStorm 8y agoThe right equivalent is actually punning through char* and enforcing lack of simultaneous aliasing. This is explicitly allowed in C++11. Memcpy is a cost. Do it only when you actually need a copy.
- saagarjha 8y agoAll half-decent compilers elide a memcpy when you're using it for this purpose; they'll just generate the assembly you "intended" to create. And while I know casting to a char * is legal for all types, I don't believe casting from a char * is legal unless the memory the pointer references is actually the type you're casting to. I'll have to check on this–or if you have a link to the standard on this I can just look at that.
- gshrikant 8y agoI'm curious, AFAICT Linux uses -fno-strict-aliasing with GCC which promises not to enable strict aliasing based optimizations even at higher optimization levels. But they also rely on the GCC blessed behavior of union based type punning which is redundant in that case. I suppose union based type punning makes the intent a little clearer (vis a vis memcpy) but that's a weak argument at best.
- saagarjha 8y ago> I suppose union based type punning makes the intent a little clearer (vis a vis memcpy) but that's a weak argument at best. How much more explicit can you get than a memcpy?
- gshrikant 8y agoI meant the fact that you're actually reinterpreting bits and not really copying them somewhere.