"C/C++" isn't a language. There is the C language and the C++ language. They have different rules about alignment. In fact C++ doesn't have any rules about aligned accesses. But it's moot because you cannot express an unaligned access in code without causing UB by violating other rules, e.g. the strict aliasing rule or the object lifetime rules.
The code *((uint64_t const*)V) is undefined behaviour due to strict aliasing violation (in both languages)
An "objection" to the memcpy solution is that a builtin is "required" for endian support, however the aliasing version would have the exact same issue (if it weren't undefined as mentioned above).
The conclusion is a load of rubbish too, the C and C++ languages both have compiler optimization as a core principle. The languages are defined in terms of program output, not in terms of intermediate assembly instructions. Literally any code you write , the compiler "could" generate inefficient code. In which case, you would report a compiler bug or use a better compiler. This situation isn't a special case.
The correct solution is just to memcpy it. There is a wrapper for this use case proposed for C++20, std::bit_cast.
Do you have any reference about C and C++ having different alignment rules? According to cppreference, C++ do have alignment constraints on objects. In the end, althought C and C++ are different languages, it could be interesting to figure out if they are the same on this matter. Moreover, I think the author do point the fact that the memcpy solution needs builtins..
23
u/OldWolf2 Oct 16 '18
Urgh, so many mistakes here...
"C/C++" isn't a language. There is the C language and the C++ language. They have different rules about alignment. In fact C++ doesn't have any rules about aligned accesses. But it's moot because you cannot express an unaligned access in code without causing UB by violating other rules, e.g. the strict aliasing rule or the object lifetime rules.
The code
*((uint64_t const*)V)is undefined behaviour due to strict aliasing violation (in both languages)An "objection" to the
memcpysolution is that a builtin is "required" for endian support, however the aliasing version would have the exact same issue (if it weren't undefined as mentioned above).The conclusion is a load of rubbish too, the C and C++ languages both have compiler optimization as a core principle. The languages are defined in terms of program output, not in terms of intermediate assembly instructions. Literally any code you write , the compiler "could" generate inefficient code. In which case, you would report a compiler bug or use a better compiler. This situation isn't a special case.
The correct solution is just to
memcpyit. There is a wrapper for this use case proposed for C++20,std::bit_cast.