C++ Logo


Advanced search

[std-proposals] this return type

From: Jan Schultke <janschultke_at_[hidden]>
Date: Fri, 7 Apr 2023 19:14:29 +0200
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:

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.

Received on 2023-04-07 17:14:41