cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

Deducing this by value or reference?

Open BluBb-mADe opened this issue 3 years ago • 2 comments

Channel

C++Weekly

Topics

I would really like to see a deeper dive into deducing this. Specifically questions like when to take self as value or rvalue reference. How these differ and behave in practice. I am interested in how they get optimized especially when capturing self by value. Would that, at least in theory, allow compilers to more effectively optimize because value semantics are generally easier to reason about for compilers? I have seen self by rvalue ref quite a bit in many examples but how exactly this feature interacts with perfect forwarding is quite opaque to me still.

This of course is a very new feature with very little compiler support so far, so it might be a good idea to leave this topic for the future when implementations have caught up and the implications have been explored more fully.

Length

I am not sure how much subtlety there is in the answers to these questions so it really depends on how deep the topic goes. My intuition tells me it's a quite complex topic that would require a longer video but I very much lack the expertise to judge it properly.

BluBb-mADe avatar Feb 24 '23 12:02 BluBb-mADe

Find this with growing compiler support really interesting as well. Here a tiny snippet of toy-code were I am experimenting around with the same questions @BluBb-mADe raised:

https://compiler-explorer.com/z/axKhTErMj

Sy Brand has some good introduction for this but goes not really in the detail I would hope

https://devblogs.microsoft.com/cppblog/cpp23-deducing-this/

seichter avatar Jun 20 '24 08:06 seichter

The main difference is that this auto self forces the move whereas this auto&& self uses perfect forwarding rules and reference collapsing. However, you don't necessarily have to make it deduce anything, this ClassName&& self will always require calling by move for example, even if the value is never moved from. To get this same behavior with a deduced type, you have to constrain the template function to forbid calling by Lvalue reference instead of by move, such as by using requires. Also note that an explicit object parameter can never give the same behavior as an implicit object parameter member function that has neither & nor && qualification - such an implicit object parameter function can be called from an rvalue or an Lvalue reference without having to be a template, whereas explicit object parameter syntax requires being a template (or having multiple overloads) to achieve that same capability.

LB-- avatar Jun 26 '24 15:06 LB--