void PrintName(string&& name) {
cout << "[rvalue] " << name << endl;
}
void PrintName(string& name) {
cout << "[lvalue] " << name << endl;
}
int main() {
string name{"Charles"};
PrintName(name); // [lvalue] Charles
PrintName("Charles"); // [rvalue] Charles
}
I overloaded the PrintName
to accept both the rvalue and lvalue.
When I call it with a lvalue name
, it works fine and outputs [lvalue] Charles
;
When I call it with "Charles"
directly, it chooses to run the rvalue version and outputs [rvalue] Charles
.
However, I heard that the string literal is lvalue, so why doesn't "Charles" call the lvalue version of the PrintName
?
And, how can we write some code to prove that the string literal is lvalue?
With the help of the comments and answers, I finally figured out to write a piece of code to prove that a string literal is a lvalue
typedef const char stringliteral[8];
void PrintName(stringliteral&& name) {
cout << "[rvalue] " << name << endl;
}
void PrintName(stringliteral& name) {
cout << "[lvalue] " << name << endl;
}
Call PrintName
by "Charles"
will run the rvalue version.