C++ Logo

std-proposals

Advanced search

Re: [std-proposals] this return type

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Sun, 09 Apr 2023 09:59:41 +0100
On Fri, 2023-04-07 at 19:14 +0200, Jan Schultke via Std-Proposals
wrote:
> For many operator overloads like assignment or pre-increment, as well
> as builder pattern functions, you tend to write:
> return *this;
>
> What if we could write the following:
> struct T {
> int i;
> this operator++() { ++i; }
> };
>
> A return type of `this` would result in an implicit return T by
> reference, with qualifiers taken from the function (e.g.
> const-qualified member functions return const T&). This saves one
> line
> of boilerplate in many places, saves developers from forgetting to
> return *this, and can improve performance.
>
> Namely it improves performance because it can help with
> devirtualization:
> x.fun1().fun2().fun3()
>
> If three virtual member functions return T&, that T& may not be a
> self-reference, so it requires a vtable lookup each time. If the
> member functions return "this", then the dynamic type must stay the
> same and the second and third call can use the same vtable pointer.

Shouldn't compilers optimise this similarly to cache the vtable
pointer?

https://godbolt.org/z/zxj7nxr9s

It looks like they don't reuse the vtable/function pointer they get for
the first call, and I don't know why.

Cheers,
Lénárd

Received on 2023-04-09 08:59:50