C++ Logo

std-discussion

Advanced search

Re: Is it valid use reinterpret_cast to form pointer to object?

From: Mykola Garkusha <garkusha.mykola_at_[hidden]>
Date: Sun, 6 Aug 2023 01:30:35 +0100
This is still an inconclusive answer, which is the central question on this
thread really.

alignas(T) std::byte storage_[sizeof(T)];
T *ptr_ = ::new (&storage_) T;
T* ptr2 = reinterpret_cast<T *>(&storage_)

Is using ptr2 well-defined just on the grounds that according to the
aliasing rules accessing objects through std::byte, unsigned char or the
DnamicType is well-defined?

On the contrary, the following is not well-defined and would need
std::launder to provide the correct behavior given the size and
alignment for T1 and T2 match.?

T1 storage;
T2 *ptr_ = ::new (&storage_) T2;
T2* ptr2 = reinterpret_cast<T2 *>(&storage_) // UB?
T2* ptr2 = std::launder(reinterpret_cast<T2 *>(&storage_)) // well-defined?
ptr->~T2();
::new (&storage_) T1; //needed if T1 got non-trivial destructor


On Tue, Aug 1, 2023 at 8:00 AM Ville Voutilainen via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> On Tue, 1 Aug 2023 at 08:58, Lénárd Szolnoki via Std-Discussion
> <std-discussion_at_[hidden]> wrote:
> > The need for launder is much more clear regarding compiler optimisations
> if the same storage is used to hold different objects during its lifetime.
> But you technically need it when the storage only ever holds a single
> object.
>
> Well.. in the OP example, the storage first has an array of std::byte
> in it, and then has a T in it.
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>

Received on 2023-08-06 00:30:48