C++ Logo

std-discussion

Advanced search

Re: std::launder question

From: Ryan Nicholl <exaeta_at_[hidden]>
Date: Mon, 21 Feb 2022 21:35:32 +0000
Assuming that we allocate some storage such that there is space for multiple T e.g.

T* foo_array = (T*) malloc(sizeof(foo)*20);

Then if we construct

new (foo_array+5) T(...);
then
*std::launder(foo_array+5)
is valid

But is

std::launder(foo_array)[5]

also valid?

Sent from ProtonMail mobile

-------- Original Message --------
On Feb 21, 2022, 15:05, Jason McKesson via Std-Discussion wrote:

> 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.
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]g
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion

Received on 2022-02-21 21:35:42