C++ Logo

std-proposals

Advanced search

Re: [std-proposals] this return type

From: Jan Schultke <janschultke_at_[hidden]>
Date: Sat, 8 Apr 2023 02:20:09 +0200
> struct A {
> this f();
> this g();
> this h1(bool b) { if (b) return f(); }
> this h2(bool b) { if (b) return f(); return g(); }
> };

Allowing this form of return statement would be good for ergonomics,
but introduces one (or more special cases).
What about a return (c ? f() : g()) ? Making this undefined behaviour
makes most sense to me, now thinking about it.

This would also make the return statement less magical. You would have
to correctly return std::move(*this) when needed.

> struct R2 {
> this f() { } // OK, returns R2&
> this g() && { } // OK, returns R2& or R2&&; or hard error?
> this h() const { } // OK, returns const R2& ?
> };
g() should return R2&&, and h() should return const R2().

> I had tacitly assumed that `R2::h` would be well-formed and return `const R2&`. But that should have been one of my explicit questions.
The decision was made explicitly const-qualifying the member
functions, so I don't see a problem. You would need to const_cast to
return something R2& normally anyways, so const R2& seems like the
sane default to me.

Keeping all cvref qualifications is the most simple and consistent
rule. You could make the argument that after an object was moved from,
it is no longer something you typically want to move from, so
returning an lvalue reference is better. However, using an object
right after it was moved from is typically a mistake regardless.
Either behaviour shouldn't have any obvious pitfalls, given that
moved-from types must be left in a valid state, and that state is
typically implemented as an empty state.

Received on 2023-04-08 00:20:21