Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between rvalue reference and lvalue reference as argument

After reading the post:http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html.

I can not figure out that when you write functions that take lvalue or rvalue references as arguments, such as this:

void printReference (const string& str)
{
    cout << str;
}

void printReference (string&& str)
{
    cout << str;
}

why the first printReference function could accept any argument, whether it be an lvalue or an rvalue, and regardless of whether the lvalue or rvalue is mutable or not. However, in the second printReference function, just allow to pass mutable rvalue.

May be my understanding is wrong, could anyone help me figure out it.

like image 976
sydridgm Avatar asked Nov 20 '15 14:11

sydridgm


1 Answers

The first option can take lvalues because it's an lvalue reference. It can take rvalues because it is marked const and rvalues are allowed to bind to const lvalue references.

The second version is only allowed non-const rvalues because you can't implicitly strip const from the referencee and rvalue references don't allow lvalues to bind to them.

The semantic difference is that the former function is saying "I am just going to read what you pass in here and I'd rather not copy it", whereas the latter is saying "I reserve the right to rip the guts out of this object and paint my living room with them".

like image 167
TartanLlama Avatar answered Sep 21 '22 13:09

TartanLlama