What exactly happens when we use rvalue references and how does std :: move work?

advertisements

I am trying to understand rvalue reference and move semantics. In following code, when I pass 10 to Print function it calls rvalue reference overload, which is expected. But what exactly happens, where will that 10 get copied (or from where it referred). Secondly what does std::move actually do? Does it extract value 10 from i and then pass it? Or it is instruction to compiler to use rvalue reference?

void Print(int& i)
{
    cout<<"L Value reference "<<endl;
}

void Print(int&& i)
{
    cout<<"R Value reference "<< endl;
}

int main()
{
    int i = 10;

    Print(i); //OK, understandable
    Print(10); //will 10 is not getting copied? So where it will stored

    Print(std::move(i)); //what does move exactly do

    return 0;
}

Thanks.


But what exactly happens, where that 10 will get copied (or from where it referred)

A temporary value is created, and a reference passed to the function. Temporaries are rvalues, so can be bound to rvalue references; so the second overload is chosen.

Secondly what std::move actually do?

It gives you an rvalue reference to its argument. It's equivalent (by definition) to static_cast<T&&>.

Despite the name, it doesn't do any movement itself; it just gives you a reference that can be used to move the value.