C++ Logo

std-discussion

Advanced search

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

From: Brian Bi <bbi5291_at_[hidden]>
Date: Mon, 31 Jul 2023 16:35:15 -0400
On Mon, Jul 31, 2023 at 3:46 PM Артём Колпаков via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> Good day. I hope someone can help me figure it out.
>
> 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_)
>
> I can't figure out if the second application is valid in general, or is it
> UB? It seems that the standard of the language through prescriptions in
> various places prohibits this. If valid, then from which place of the
> standard does this follow? If not, will the use of std::launder help here,
> or is it for other cases? Can anyone give a link to articles on this
> subject?
>

You do need to call `std::launder` after the `reinterpret_cast` because the
object that is nested within the `storage_` array is not
pointer-interconvertible with it.

The standard library can omit `std::launder` if the implementors know that
the compiler does not actually care whether or not `std::launder` is used.
I'm not aware of any compiler that currently optimizes based on the
assumption that an unlaundered pointer cannot be validly used to access an
object.


>
> Thank you for your attention.
> Artyom Kolpakov
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>


-- 
*Brian Bi*

Received on 2023-07-31 20:35:29