What is not fine is pretending that an object lives at a position in memory where it does not (i.e. treating bytes of memory as some object through a reinterpret_cast away from char* ).
Edit: To clarify, casting away from char* is of course allowed if you cast to whatever object type actually lives at the pointed-to location.
It seems like the function only cast to T* if the input pointer hasn't been changed (the paths that do modify it return early), so there's a value there?
It is only fine if there were the same exact int types at that address. Remember, UB usually isn't the reinterpret_cast but the dereference.
And now std::byte IIRC
That is correct. See my other nearby reply.
> So casting to char* and back is fine
Indeed.
> casting to char and then to int-type to inspect multiple bytes is fine as long as alignment plays correctly, ...
Only if the place in memory you are pointing to actually has a live int object. In particular, inspecting the byte representation of an object is fine (including copying the bytes elsewhere, which is why they could just use memcpy instead of reinterpret_cast).
See also http://eel.is/c++draft/basic.types#2 and surroundings.
That's how people have used C and C++ for decades in low-level work, and it still works exactly as you'd expect, so stop saying "don't do it" because you're only encouraging the compiler-writer-UB-optimisation-nonsense crowd to make things even worse. It's already bad enough that they think the Holy Standard is the only thing that matters.
I believe Linus has several memorable rants on this topic already.