C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Make all data pointers intercompatible

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Thu, 9 May 2024 11:00:22 +0100
I reply to Jonathan, Sebastian and Tiago in series below.


On Thu, May 9, 2024 at 10:16 AM Jonathan Wakely wrote:
>
> As usual, you haven't provided a reason why doing that
> would be useful. All you've said is it might be possible.


Use Case 1:

Early this year I shared a paper on "std::unaligned":

    http://www.virjacode.com/papers/unaligned_latest.pdf

When I was writing the class "std::unaligned", I was considering
storing the address of an unaligned T inside a T*. I'll give a
hypothetical architecture:
    T = int
    CHAR_BIT == 16
    sizeof(int) == 2
    UINT_MAX == 4294967295

So int's are 32-Bit, and the smallest addressable unit of memory is 16
bits. So if you have an array of three int's, the respective addresses
of the 3 ints are:
    0x2000
    0x2002
    0x2004

The memory address 0x2001 would be an int unaligned by 16 bits, but
there's no way of specifying an int unaligned by 8 bits. Therefore
this platform can be described as follows:
    (1) sizeof(char*) > sizeof(int*)
    (2) You cannot store the address of an unaligned T inside a T*

However . . . in the future . . . if C++26 were to mandate that all
data pointers are intercompatible, then we could store the address of
an unaligned T inside a T*.

Nit Pick: The platform described above could have sizeof(char*) ==
sizeof(int*) if the latter type has extra bits that are always zero.


On Thu, May 9, 2024 at 10:47 AM Sebastian Wittmeier wrote:
>
> What do you mean by intercompatible? Same size, representation and alignment? Or conversion between any of them, even if the types are not interconvertible?


Same size, same representation, same alignment. So you can do the following:

    char *Func(char *arg)
    {
        double *p1 = (double*)arg;
        int *p2 = (int*)p1;
        std::string *p3 = (std::string*)p2;
        return (char*)p3;
    }

The above function would be well-formed with well-defined behaviour,
and it could be compiled on x86_64 Linux to a single instruction:

    mov rax, rdi // Copy 1st argument to return value


On Thu, May 9, 2024 at 10:52 AM Tiago Freire wrote:
>
> Did you ever work on a system where sizeof(int*) != sizeof(char*)?
> Me neither.
> So, I'm not sure there's an issue to be solved. If someone has that
> problem, then they can let us know, and we will look at specifics then.


So if there's no compilers in existence anymore with sizeof(char*) >
sizeof(int*) then we could make allow data pointer intercompatibilty.

Received on 2024-05-09 10:00:34