0

I understand the following code, but just wondering what is the benefit of such a feature? I understand the performance benefit of a function argument taking a && - r-value reference instead of an l-value, but don't get the following case where the function being called is decided based on whether the object is r-value reference or l-value.

#include <iostream>
    class SomeClass {
    public:
      int f() & { std::cout << "lvalue\n"; }
      int f() && { std::cout << "rvalue\n"; }
    };
    int main() {
        SomeClass s; s.f(); // prints "lvalue"
        SomeClass{}.f(); // prints "rvalue"
    }
user3219492
  • 540
  • 6
  • 17
  • If the function is called as rvalue then there is good possibility it is a temporary in which case it might optimize calls by releasing memory/ownership. But not sure if this is recommended to do. – ALX23z Dec 09 '20 at 03:58
  • @TrebledJ Thanks. My understanding: whenever I write a member function, the first argument of the member function is of type of the class, and this change is made by the compiler. So, in this case, compiler changes my functions to SomeClass::f(SomeClass&) and f(SomeClass&&). Now, f.f() calls first and SomeClass{}.f() calls later. So, in the later case, un-necessary copy of the temporary object is avoided. Am I correct? – user3219492 Dec 09 '20 at 04:43
  • 1
    I don't follow... No copying is done here at all. (Or were you referring to the unique_ptr example in the other question?) & and &&-qualifiers work the same way as const qualifiers. With const-qualifiers, you get the assumption (or provide the guarantee) that the `this` object is const. Similarly, with &/&&, you get the assumption that `this` is lvalue or rvalue, so you can make certain optimisations. So yes, you can the && overload to avoid unnecessary copies. – TrebledJ Dec 09 '20 at 04:51

0 Answers0