C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Wed, 06 Dec 2023 15:03:23 -0800
On Wednesday, 6 December 2023 14:20:18 PST Frederick Virchanza Gotham via Std-
Proposals wrote:
> 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:

string_view does not change what a string is.

>
> #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 */
> }

Donkey isn't a primitive. If std::unaligned is allowed on non-primitives like
that, then the code above would work with no alignment faults.

But sizeof(Donkey) is still 32.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DCAI Cloud Engineering

Received on 2023-12-06 23:03:26