C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Disable assignment to an rvalue

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Mon, 17 Oct 2022 17:31:43 +0100
Hi,

On 17 October 2022 12:38:32 BST, "Peter Sommerlad (C++) via Std-Proposals" <std-proposals_at_[hidden]> wrote:
>FWIW, MISRA-C++ and me propose to define (copy/move) assignment
>operators to be lvalue-ref-qualified, at least when you must define
>those, because you are implementing a manager type. This is in line with
>"when in doubt, do as the ints do" (Scott Meyers), because with the
>fundamental types you cannot assign to an rvalue.

I think this is a disciplined take for value types, but for reference types it might not be adequate.

>
>my classical example of leaking lvalue references is:
>
>struct X{};
>
>auto & dangle = (X{} = X{});

The main issue here seems to be to return a reference from the assignment at all. And if `rvalue = something` returns a reference, it should better be an rvalue reference. If the object is expiring, then it is still expiring after you assign to it.

>
>That we have unqualified member functions like front/back on containers
>that could be called on rvalues and deliver lvalue references is a pity,
>but that is something where changing the library to delete the
>rvalue-qualified overload or make it return by value might be too much work.
>
>But for my own types I'll follow the practice of ref-qualifying member
>functions with side effects and returning references to guts accordingly.
>
>I don't know yet, how that will change with deducing this in C++23.
>
>Note, that I don't propose all overloads of any assignment operator to
>be lvalue-ref-qualified, because a type might be defining a DSL where
>such things might not have side effects or potentially return an lvalue
>reference to an rvalue.
>
>Regards
>Peter.

Cheers,
Lénárd

Received on 2022-10-17 16:31:47