C++ Logo

std-proposals

Advanced search

Re: [std-proposals] this return type

From: Thiago Macieira <thiago_at_[hidden]>
Date: Sat, 08 Apr 2023 09:06:55 -0300
On Friday, 7 April 2023 14:14:29 -03 Jan Schultke via Std-Proposals wrote:
> Namely it improves performance because it can help with devirtualization:
> x.fun1().fun2().fun3()

Do we need to change the syntax for declaring what those functions return or
do we need a way to make the statement above more efficient? The case of
operator++ doesn't really matter here because they're almost never virtual and
they're almost always inline in the first place. Though I do note that it's not
necessary for it to be virtual for this to be useful.

So what if instead we fixed the call chain above, or had a simpler syntax to
reuse the same object? Such as:

  x.(fun1(), fun2(), fun3());

Maybe even make it statement-like:
  x.{
     fun1();
     if (fun2())
         fun3();
  };

This would in turn allow each of those functions to return something other
than this and be useful in other scenarios. For example, QString::replace()
returns QString & (a *this reference) so you could write:

 qsizetype n = str.replace("foo", "bar").replace("\\", "\\\\").indexOf("xyz");

But if we had had a syntax for call-chaining of the same object,
QString::replace() would probably have returned the number of replacements
made, which is a far more useful result when you're *not* chaining.

And if changing the call syntax is not a possibility, this does sound like a
good use of an attribute:

  [[returns_this]] QString &replace(const QString &a, const QString &b);

  [[returns_this]] Derived *f() override;

That would allow an update of existing uses without ABI breaks, does not
introduce a new syntax, and does permit the optimisations discussed by
declaring that it's UB to return something other than *this (like returning
from a [[noreturn]] function). The drawback is that it adds to what one must
type, but I find it arguable that the proposed, shorter syntax is actually
*better* by suppressing the return statement.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DCAI Cloud Engineering

Received on 2023-04-08 12:06:58