6 ms·
It's not really surprising that invalid code doesn't go along with compiler optimizations. The correct way to deal with this here is probably either _NOT_ usin
by dklsf 11y ago
It's not really surprising that invalid code doesn't go along with compiler optimizations.
The correct way to deal with this here is probably either _NOT_ using nullptr, and instead using a special null object (similar to the end iterator); or using pointers instead of references (because you really want pointer behaviour).
Their fix is insane, and not something I'd want in production code. Unless you carefully vet your code and compiler version, you should never rely on undefined behaviour.
(There are some cases in the c standard that technically undefined but all compiler vendors have essentially agreed to handle in the same way; so those are fine. IIRC unions are a common example.)
- throwaway999888 11y agoThe author should just be glad that his code didn't launch any missiles.
- Kristine1975 11y agoJohn Regehr did a contest in 2012: Craziest Compiler Output due to Undefined Behavior: http://blog.regehr.org/archives/759 http://blog.regehr.org/archives/759 No launched missiles though.
- Kristine1975 11y agoIIRC unions are a common example. If you mean type punning: That is fine in C (chapter 6.5.2.3 of the C11 Standard even mentions "type punning" in footnote 95), but not in C++, where it's undefined behavior. I would just use memcpy. It works even when C code is compiled as C++, and modern compilers know what memcpy does and can optimize its call to a move operation: http://blog.regehr.org/archives/959 http://blog.regehr.org/archives/959
- barrkel 11y agoType punning is not fine in C99 - you need to use a correctly typed pointer or a char pointer.
- Kristine1975 11y agoYou're right. Type punning via pointer cast, e.g. int i = ... float f = *(float*) &i; is not fine (violates strict aliasing). Type punning via union, e.g. union { int i; float f; } u; u.i = ... float f = u.f; is, though (but only in C). Just use memcpy :-)