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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With