C++ Logo


Advanced search

Re: [std-proposals] this return type

From: Jan Schultke <janschultke_at_[hidden]>
Date: Sat, 8 Apr 2023 11:17:56 +0200
> but you can use auto and decltype(*this) if you use the training return type. Bonus: the return type honors the function constness like you wanted.

You can write that, but it's obviously a bit verbose and developers
are unlikely to choose that option over being explicit. It honors
cv-qualifiers, but doesn't honor rvalue-reference qualifiers because
*this is always an lvalue.

> Your idea also ONLY works IF you can see the internals of those methods. The implementation might not be in the header and might return something other than you expected.

I don't see how? The "this" return type would be a contract that
guarantees that a reference to the same object is returned. Since
objects cannot change in dynamic type at runtime, this prevents
re-virtualization. Even if the definition of the virtual function is
not visible, you can perform this optimization.

> Your idea about presuming the address does not change would fail with multiple inheritance even though you're still dealing with the same object just a different base or the derived type itself, the address is potentially different.

The return type of the "this function" is a (cv-rvalue-qualified)
reference to T, where the "this function" was declared in T. It cannot
be a reference to one of its bases or the derived type, since this
would make the program ill-formed by the current language rules. You
could return a reference to the derived type in an overriding
function, but this is just getting up-cast as usual, when calling
through the base function.

Received on 2023-04-08 09:18:09