C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Relocation in C++

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Fri, 6 May 2022 11:40:57 +0100
On Fri, 6 May 2022 at 11:16, organicoman <organicoman_at_[hidden]> wrote:

> The resource will continue to be managed, but by a different object; the
> lvalue object materialized from the prvalue relocated from the original
> owner lvalue. So it will be released when the new object's destructor is
> called.
>
> It sounds like a garbage collection mechanism.
> Can you please illustrate with an example how we keep track of the
> resources from the first object which was relocated-from (let's name it the
> 'relocation source')?
>

Using library APIs:

alignas(unique_ptr<int>) byte buf[sizeof(unique_ptr<int>)];
auto& a = construct_at(reinterpret_cast<unique_ptr<int>*>(buf), new int);
// #1
auto const b = relocate(&a); // #2

#2 ends the lifetime of a by relocation into a prvalue materialized as b.
Since the lifetime of a has ended, buf no longer provides storage for an
object, and it is correct not to call destroy_at(&a). The resource
allocated at #1 and initially owned by a is now owned by b, and released in
its destructor.

Using operator reloc:

auto const c = unique_ptr<int>(new int); // #3
auto const d = reloc c; // #4

#4 ends the lifetime of c by relocation into a prvalue materialized as d.
Since the automatic variable c was relocated, its destructor will not be
called at the end of its scope and odr-use of its identifier is ill-formed
for the remainder of the scope. The resource allocated at #3 and initially
owned by c is now owned by d, and released in its destructor.

Received on 2022-05-06 10:41:09