c++ - 将右值引用传递给右值引用参数时发生错误

标签 c++ c++11 pass-by-reference rvalue-reference rvalue

我有代码

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/

相关文章:

c++ - 为什么我的 vector 代码断言?到底什么是断言?

c++ - 使用命名空间和包含

c++ - 对 std::multiset 中的相等范围进行排序

c++ - 交换后 vector 会保持连续吗?

c++ - 为什么 std::bind 在绑定(bind)到成员函数时无法编译?

C++初学者如何使用GetSystemTimeAsFileTime

c++ - C++中的拆分函数

linux - 为 pthread 函数传递结构指针 als 参数

c++ - 通过引用传递和返回参数时的整体提升?

perl - 为什么引用数组的值没有改变?