我有代码
void print(string &&str) {
cout << str << endl;
}
int main() {
string tmp("Hello");
string&& str = move(tmp);
//print(move(str));
print(str);
return 0;
}
编译后我得到 error: cannot bind rvalue reference of type 'std::__cxx11::string&&' to lvalue of type 'std::__cxx11::string'
.
但是str
r-value 是对 r-value 的引用(不是吗?),因此将其传递到 print
我相信这是有道理的。为什么会出现这个错误?
最佳答案
您对 value categories 感到困惑和类型。
(强调我的)
lvalue
The following expressions are lvalue expressions:
- the name of a variable or a function in scope, regardless of type, such as std::cin or std::endl. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;
- ...
str
的类型是右值引用(对 string
),但作为命名变量,它是一个左值,不能绑定(bind)到右值引用。
如果允许,请考虑以下情况:
string tmp("Hello");
string&& str = move(tmp);
print(str); // str might be moved here
cout << str << endl; // dangerous; str's state is undeterminate
因此,如果您确定效果,则需要显式使用 std::move
(将 str
转换为 xvalue) .
关于c++ - 将右值引用传递给右值引用参数时发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43115063/