C++ Logo

std-discussion

Advanced search

Re: std::launder question

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Mon, 21 Feb 2022 15:05:03 -0500
On Mon, Feb 21, 2022 at 2:42 PM Ryan Nicholl via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
> C++ std seems to make it clear that:
>
> *std::launder(foo+4)
>
> works if foo is a pointer to storage.
> Does :
>
> std::launder(foo)[4]
>
> Also work?

`std::launder` is used for cases where there is an object of type `T`
at a location of memory, but for whatever reason you have a pointer to
that location which is not a pointer to that particular `T`. It
therefore converts your pointer into a pointer to that `T`.

`std::launder` does not work if there isn't a `T` there. So I don't
know what you mean by "a pointer to storage" (though C++20's implicit
object creation can make `launder` work for that case, but it would do
so for a `reinterpret_cast` too).

In any case, if the object you're getting a pointer to is an element
of an array, then `launder(foo)[4]` will retrieve the 4th element from
that object in the array, if any. `launder(foo + 4)` may or may not
work, depending on what `foo` actually points to.

Received on 2022-02-21 20:05:15