C++ Logo

std-proposals

Advanced search

Re: [std-proposals] [[packed]]

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Wed, 6 Dec 2023 22:20:18 +0000
On Wed, Dec 6, 2023 at 5:26 PM Thiago Macieira wrote:
>
> It is just allowed to remain unaligned
> wherever it is placed in memory if used as std::unaligned<Monkey>.
>
> If you want to remove the internal padding, use std::unaligned in the members
> of your Monkey struct.


I thought maybe 'std::unaligned' was intended as a handle, in similar
vain to how a 'string_view' refers to a string, sort of like this:

    #include <cstdlib> // malloc
    #include <cstring> // memcpy

    struct Donkey {
        long double a;
        int b;
    };

    int main(void)
    {
        Donkey *p = static_cast<Donkey*>( std::malloc(sizeof(Donkey) + 1u) );
        p->a = 56.8L;
        p->b = 7;

        char *const q = 1u + static_cast<char*>(static_cast<void*>(p));
        std::memmove( q, p, sizeof(Donkey) );

        std::unaligned<Donkey> chocolate(q); /* 'chocolate' acts as
a handle to what exists at 'q' */
        chocolate->a = 34.7L; /* No alignment access error here */
    }

Received on 2023-12-06 22:20:31