C++ Logo

std-proposals

Advanced search

Re: [std-proposals] this return type

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Sat, 8 Apr 2023 17:34:11 -0500
On Sat, 8 Apr 2023 at 04:18, Jan Schultke via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> > 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.
>

If this is about contracts and optimizing for opaque functions, maybe we
can do this with contracts?

[[post assume r: &r == this]]

Unfortunately gcc doesn't yet appear able to use this information:
https://www.godbolt.org/z/sn7a1ze5K

> 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.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2023-04-08 22:34:25