Search code examples
c++c++11rvalue-referencelvalue-to-rvalue

How does rvalue reference work here?


I am puzzled by the following code:

#include <iostream>

int main()
{
    int x{};

    int&& rvx = static_cast<int&&>(x);
    ++rvx;
    std::cout << x << std::endl;
}

The output of it is 1. I don't understand how this works. The static_cast is supposed to cast the lvalue x into an xvalue, which is then assigned to rvx. Why does incrementing rvx lead to a change in x? Is this because the converted lvalue-to-rvalue is essentially sitting at the same memory location, but it is just considered now a rvalue? I was under the impression (which is probably false) that somehow the cast creates a temporary out of its argument.


Solution

  • An rvalue reference can bind to a temporary. This is what you'd get, for instance, if you write

    int x{};
    int&& rvx = +x;
    

    But it doesn't need to bind to a temporary. By casting x to int&&, you've indicated to the compiler that that's okay too, that it may treat x as an rvalue to bind directly to the reference.