1
void fcn(int&& a) { }
int&& reti() {
    return 3;
}
int main() {
    int&& a = 3;
    fcn(a);    //error
    fcn(reti()); //right
    return 0;
}

why does the first call generate an error, but the second call does not? they are all the int&& type.

user815129
  • 2,236
  • 2
  • 20
  • 40
air
  • 199
  • 1
  • 7

1 Answers1

1

Types and value categories are different things. Even a's type is rvalue-reference but as the name of variable a is an lvalue expression itself.

(emphasis mine)

The following expressions are lvalue expressions:

  • the name of a variable, a function, a template parameter object (since C++20), or a data member, regardless of type, such as std::cin or std::endl. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;

You can use std::move to convert it to rvalue as:

fcn(std::move(a));

On the other hand, reti returns rvalue-reference and reti() is an rvalue expression. (PS: reti() always returns a dangling reference.)

The following expressions are xvalue expressions:

  • a function call or an overloaded operator expression, whose return type is rvalue reference to object, such as std::move(x);
songyuanyao
  • 169,198
  • 16
  • 310
  • 405