C++ Logo

std-discussion

Advanced search

when to std::launder

From: Mohamed Khaled <mkmostafa92_at_[hidden]>
Date: Mon, 29 Apr 2019 10:57:24 +0200
Hello All,

```
#include <memory>
#include <iostream>

struct C
{
    const int x;
};

void foo1()
{
    C c{1};
    c.~C();
    new (&c) C{2};
    std::cout << c.x << std::endl;
}

std::unique_ptr<C> foo2_a()
{
    std::unique_ptr<C> c(new C{1});
    c->~C();
    new (c.get()) C{2};
    return c;
}

void foo2_b(std::unique_ptr<C> c)
{
    std::cout << c->x << std::endl;
}

int main()
{
    foo1();
    foo2_b(foo2_a());
}
```

As far as I understand, in foo1() one should invoke std::launder whenever c
is being accessed after the placement. Should it also be invoked in foo2_b,
that is when the access to the object whose memory is being reused is in
some separate function rather than the one where the placement happened.
More generally should the placement new always be coupled with std::launder?

Regards,
Mohamed

Received on 2019-04-29 03:59:13