C++ Logo

std-discussion

Advanced search

Is it valid use reinterpret_cast to form pointer to object?

From: Артём Колпаков <ddvamp007_at_[hidden]>
Date: Mon, 31 Jul 2023 22:46:05 +0300
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?

Thank you for your attention.
Artyom Kolpakov

Received on 2023-07-31 19:46:24