C++ Logo

std-proposals

Advanced search

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

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Mon, 2 May 2022 12:14:11 +0100
On Mon, 2 May 2022 at 11:24, Sébastien Bini via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Stating that the moved-from object is invalid and should not be touched
> again is (in my opinion) a bad class design. You may have a look at
> https://herbsutter.com/2020/02/17/move-simply/, which further motivated
> me to write this paper. Quoting Herb Sutter: "In C++, an object is valid
> (meets its invariants) for its entire lifetime, which is from the end of
> its construction to the start of its destruction (see [basic.life]/4).
> Moving from an object does not end its lifetime, only destruction does, so
> moving from an object does not make it invalid or not obey its invariants."
> Relocation allows to make an object invalid before it is destructed, albeit
> it is never touched again except by its destructor.
>

A destructor may call arbitrary methods on the class under destruction,
which will have no way to tell that the instance they are invoked on was
previously relocated. How will you ensure safety in this scenario? It seems
that there will be a considerable burden on the class author to ensure that
all methods called from the destructor are safe to be called on a relocated
instance, since the language will not ensure this, and a considerable
maintenance burden going forward.

Far better to terminate the lifetime immediately and omit calling the
destructor entirely.


> The reloc operator introduces a language-level guarantee (no use after
> relocation) that will always be better than an external tool that
> developers may simply not run.
>

If this is language-level, the language can immediately terminate the
lifetime. In the if/else case, lifetime can be terminated with a destructor
call at the end of the branch where relocation does not occur.

I am still open to discuss the syntax. I would be in favor of a solution
> that doesn't introduce a new constructor and a new type of reference, but I
> still haven't found it :/
>

Firstly, don't introduce a new value category; we already have more than
enough. If the instance lifetime is terminated immediately, there is no
need for another value category since there will no longer be an object in
its storage.

My suggestion for syntax would be *prvalue qualification* on class member
functions, with relocation implemented as prvalue qualified conversion to
the same (class) type:

struct A {
    operator A() prvalue; // or "reloc", or "~", or "&(false)", etc. -
note that the qualification position is relatively free syntax
};

Received on 2022-05-02 11:14:24