While I was studying rvalue reference, I found a strange answer from stackoverflow.
The questioner wants to avoid code duplication between a function that receive parameter as a lvalue reference, and another one is a function that receive a rvalue reference. Both functions do the same thing.
Here is the issue:-
void foo(X& x) { /*complex thing*/ } //#A
void foo(X&& x) { /*complex SAME thing*/ } //#B
Here is the proposed solution. It is modified a bit by me:-
void foo(X& x) { /*complex thing*/ } //#A
void foo(X&& x) { foo(x); } //#B
Question
Why doesn't my version lead to stack overflow exception?
In my version, why foo#B call foo#A, but not foo#B?
More specifically, which C++ rule enforces this behavior?
According to the rule of value categories, as a named parameter,
xis an lvalue. Thenfoo#Awill be invoked, becausexcould be bound to lvalue-reference, but not rvalue-reference.Note that the fact that
xis declared as an rvalue-reference has nothing to do with the value category ofx.You can use
std::moveto make it an xvalue (rvalue), thenfoo#Bwill be selected (as you expected).