4 ms·
I 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 abo
by saagarjha 8y ago
I 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.