C++ Logo

STD-DISCUSSION

Advanced search

Subject: when to std::launder
From: Mohamed Khaled (mkmostafa92_at_[hidden])
Date: 2019-04-29 03:57:24


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



STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups