As I understand it, ref-qualified member-functions are used to distinguish between operating on an implicit this
as an lvalue versus an rvalue. If we define a member function without the ref-qualification, then both lvalues and rvalues call the same member function. For example
class Obj {
public:
Obj(int x) : x_{x} {}
int& getVal() {return x_;}
};
here, doing something like Obj o{2}; o.getVal();
and Obj{2}.getVal()
call the same getVal()
function.
However, I'm not sure I understand the use case for this. I can't seem to see when we might want to treat an lvalue different from an rvalue. I was thinking perhaps rvalues might be treated as temporary variables, so maybe we don't want to return a reference to a member variable, whereas it might be ok for lvalues since they're actually stored in a memory address and can be managed better. For example,
class Obj {
public:
Obj(int x) : x_{x} {}
int& getVal() & {return x_;}
int getVal() && {return x_;}
};
I believe would return a reference to the member x_
for lvalues, and would return a copy of it for rvalues of Obj
since Obj
might be deleted after calling the function and we want to keep a copy of that returned member. However, I'd imagine then we'd also want to have an rvalue version of it in case we were to work with an rvalue reference in another function and we want to modify the member somehow.
Is my interpretation of ref-qualified member-functions correct so far?