32

While reading http://en.cppreference.com/w/cpp/language/member_functions, I came across something, I haven't seen before: lvalue/rvalue Ref-qualified member functions. What would be their purpose ?

newprint
  • 6,936
  • 13
  • 67
  • 109

1 Answers1

56

Just read down below:

During overload resolution, non-static cv-qualified member function of class X is treated as a function that takes an implicit parameter of type lvalue reference to cv-qualified X if it has no ref-qualifiers or if it has the lvalue ref-qualifier. Otherwise (if it has rvalue ref-qualifier), it is treated as a function taking an implicit parameter of type rvalue reference to cv-qualified X.

Example

#include <iostream>
struct S {
    void f() & { std::cout << "lvalue\n"; }
    void f() &&{ std::cout << "rvalue\n"; }
};
 
int main(){
    S s;
    s.f();            // prints "lvalue"
    std::move(s).f(); // prints "rvalue"
    S().f();          // prints "rvalue"
}

So during overload resolution the compiler looks for the function &-qualified if the caller object is an lvalue or for the function &&-qualified if the caller object is an rvalue.

Community
  • 1
  • 1
FKaria
  • 1,012
  • 13
  • 14
  • 27
    How much better a place this world would become if all the inhuman standardese was augmented with a clear and concise example! – sunny moon Feb 22 '17 at 11:10
  • I can't test with C++98. Is this after C++11 ? – Nick Oct 21 '18 at 07:07
  • 1
    @Nick, yes it is –  Feb 22 '19 at 07:24
  • @sunnymoon Could you please explain the quotation in simple words for me? – John Apr 07 '22 at 02:18
  • @John Basically, you can overload class or struct member functions on the basis of what an instance of that class will be - an lvalue (locator-value, think _'named'_, _'long-lived'_ or _'located at some named area of memory in stack or heap'_) or rvalue (i.e. non-locator-value, think _'anonymous'_, _'temporary'_ or _'located at a temporary memory area, maybe a processor register_'). That's why an lvalue `S`'s `f()` prints `"lvalue"` and rvalue `S`'s `f()` prints `"rvalue"`. Ref-qualifiers are those `&` (lvalue) and `&&` (rvalue) after `void f()`. – sunny moon Apr 08 '22 at 08:57
  • The ref-qualified member selected is based on whether 'this' in the function is an lvalue or an rvalue. The use of the technical term "caller object" means "this". – rm1948 Jan 15 '23 at 18:49