首先,常量右值引用并不是很有用,因为你不能移动它们。移动值需要可变引用才能工作。
让我们以你更正的例子为例:
void write_lvalue(std::string const& text) {
//...
}
void write_rvalue(std::string&& text) {
//...
}
int main() {
write_lvalue("writing the Lvalue");
write_rvalue("writing the Rvalue");
}
在这种情况下,两者完全等价。在这两种情况下,编译器必须创建一个字符串并通过引用发送它:
int main() {
// equivalent, string created
// and sent by reference (const& bind to temporaries)
write_lvalue(std::string{"writing the Lvalue"});
// equivalent, string created
// and sent by reference (&& bind to temporaries)
write_rvalue(std::string{"writing the Rvalue"});
}
那么为什么要有接受右值引用的函数呢?
这取决于你对字符串做什么。可以从以下位置移动可变引用:
std::string global_string;
void write_lvalue(std::string const& text) {
// copy, might cause allocation
global_string = text;
}
void write_rvalue(std::string&& text) {
// move, no allocation, yay!
global_string = std::move(text);
}
那么为什么要使用右值引用呢?为什么不使用可变左值引用?
这是因为可变左值引用不能绑定到临时对象:
void write_lvalue_mut(std::string& text) {
// move, no allocation... yay?
global_string = std::move(text);
}
int main() {
std::string s = /* ... */;
write_lvalue_mut(std::move(s)); // fails
write_lvalue_mut("some text"); // also fails
}
但是可变右值引用可以绑定到右值,如上所示。