C++ Logo


Advanced search

Re: [std-proposals] this return type

From: Andrew Tomazos <andrewtomazos_at_[hidden]>
Date: Sat, 8 Apr 2023 04:51:20 +1000
The "saving one line of boilerplate" I don't think is even worth mentioning.

Forgetting to type "return *this" is not a big deal, the toolchain will
catch that.

The performance benefit is an interesting claim, and may give this proposal
legs if it is true. I think you should implement this as a non-standard
extension and then do a performance test comparing between a real world
class that uses chaining using this feature vs without.

On Sat, Apr 8, 2023 at 3:14 AM Jan Schultke via Std-Proposals <
std-proposals_at_[hidden]> 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.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2023-04-07 18:51:34