Okay, say I have a typed pointer to a buffer of T, and I want to access its memory as both T and U, interleaved with each other. So, type-punning.
If I understand correctly, you are saying I should
(i) Get a raw pointer to the same memory.
(ii) Load individual bytes to construct a U (or in the future, perform an unaligned load).
(iii) When done with that instance of U, store it back (currently byte-for-byte).
(iv) Repeat those operations, interleaved with normal accesses through the original pointer.
Already, the original T-typed pointer and the raw pointer clearly alias, so the compiler cannot optimize as aggressively as if they did not. That’s fine, they really do alias.
• • •
That seems needlessly clunky to me.
I can picture an API along the lines of “Given a typed pointer, create a type-punned pointer aliasing it.”
The compiler would know they alias, just like the raw pointer version, so there’s no change to performance or correctness. But there is a substantial simplification for the programmer:
(i) Get a typed-punned pointer to the same memory.
(ii) Use bother pointers to read and write as desired.
• • •
I could be misunderstanding, but the impression I get is that some of the people most familiar with low-level pointer programming here, are opposed to making such a simple API, for reasons I do not grasp.
As near as I can tell, those reasons sound a lot like, “I wish it were never necessary, therefore I do not want to make it easy to do correctly.”
But for users of the language, the result of not making it easy to do correctly, is that it ends up being done incorrectly, which from my perspective is what we should really strive to avoid.
The way to avoid incorrect type-punning is not by making all type-punning difficult, but rather by making correct type-punning easy.
• • •
Edit: perhaps you were saying “Step (iv) should actually be more loads and stores from the raw pointer, to construct instances of T.”
In that case, with everything going through the raw pointer, there would no longer be aliasing problems, which is great. But then the programming experience is even clunkier.
The equivalent simple API would be a type-punning pointer that can access its memory as either T or U.
The point remains: whatever the actual recommended semantics, we can make it easy for programmers to do correctly.