C++ Logo

std-discussion

Advanced search

Re: A lifetime question about start_lifetime_as

From: Jennifier Burnett <jenni_at_[hidden]>
Date: Tue, 08 Jul 2025 15:41:36 +0100
Aside from the fact that `float` isn't necessarily 32 bits, and that the standard allows that `float` may have stronger alignment requirement than `uint32_t`, both of which could make the example illegal, it is not legal to access `data` as a `uint32_t` after reusing it's storage for a `float` because you cannot access storage occupied by one type as another unless they're compatable (i.e. int and const int, or int and unsigned int) or have specific aliasing rules making it legal (i.e. char and byte).

I'm not certain if the start_lifetime_as is in itself undefined behaviour. I would _guess_ that because `data` has an automatic storage duration there'll be an implicit `~uint32_t` at the end of the scope which might be illegal if the lifetime of data as a uint32_t has already ended, but I'm not sure how/if uint32_t being an implicit lifetime type and trivially destructible interacts with that.

On 8 July 2025 14:57:15 BST, Yongwei Wu via Std-Discussion <std-discussion_at_[hidden]> wrote:
>Assume I am working on a little-endian machine only. Is the following
>code undefined behaviour?
>
>uint32_t data = 0x40400000;
>auto f = *std::start_lifetime_as<float>(&data);
>
>If it is not, is the data variable still accessible now?
>
>Best regards,
>
>Yongwei
>

Received on 2025-07-08 14:41:47