Search code examples
c++c++11rvalue-referencepass-by-rvalue-reference

Why can't I pass an rvalue-reference as it is to another function in C++11?


I have a code:

void f(int&& i) {
  auto lambda = [](int&& j) { (void)j; }
  lambda(i);
}

int main() {
  f(5);
}

Clang++ gives an error: no known conversion from 'int' to 'int &&' for 1st argument

Why the i changes its type to int when being passed to the lambda()?


Solution

  • There are two elements at work here:

    • Type: The parameter i has type int&&, or "rvalue reference to int", where "rvalue reference" is the name for the && feature, allowing binding rvalues to a reference;

    • Value category: This is the key. i has a name and so the expression naming it is an lvalue, regardless of its type or what the standard committee decided to call that type. :)

    (Note that the expression that looks like i has type int, not int&&, because reasons. The rvalue ref is lost when you start to use the parameter, unless you use something like std::move to get it back.)