C++ Logo

std-discussion

Advanced search

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

From: Bjorn Reese <breese_at_[hidden]>
Date: Tue, 1 Aug 2023 12:08:31 +0200
On 7/31/23 21:46, Артём Колпаков via Std-Discussion wrote:

> This is a common technique:
>
> alignas(T) std::byte storage_[sizeof(T)];
> T *ptr_ = ::new (&storage_) T;
> ...
> *use* ptr_
>
> There is no problem accessing an object through a saved pointer.
> However, in many code bases, including implementations of the standard
> library (if I remember correctly, gcc), this technique is used without
> saving the pointer with further:
>
> *use* reinterpret_cast<T *>(&storage_)

Can you clarify your question please? Are you asking about this example

   alignas(T) std::byte storage[sizeof(T)];
   T *ptr = ::new (&storage) T;
   foo(reinterpret_cast<T*>(&storage));

or

   alignas(T) std::byte storage[sizeof(T)];
   foo(reinterpret_cast<T*>(&storage));

Received on 2023-08-01 10:08:33