【问题标题】:Error occurred when passing r-value reference to r-value reference parameter [duplicate]将 r 值引用传递给 r 值引用参数时发生错误 [重复]
【发布时间】:2017-08-24 05:07:09
【问题描述】:

我有代码

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&amp;&amp;' to lvalue of type 'std::__cxx11::string'

但是str 是对 r-value 的 r-value 引用(不是吗?),所以我相信将它传递给 print 是有道理的。为什么会出现这个错误?

【问题讨论】:

  • 当右值引用获得一个名称时,它会失去它的右值引用属性...

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


【解决方案1】:

您对value categories 和类型感到困惑。

(强调我的)

左值

以下表达式是左值表达式:

  • 范围内的变量或函数的名称,无论类型如何,例如 std::cin 或 std::endl。 即使变量的类型是右值 引用,由其名称组成的表达式是一个左值 表达;
  • ...

str 的类型是右值引用(对string),但作为命名变量它是左值,不能绑定到右值引用。

如果允许,请考虑以下情况:

string tmp("Hello");
string&& str = move(tmp);
print(str);               // str might be moved here

cout << str << endl;      // dangerous; str's state is undeterminate

因此,如果您确定效果,则需要明确地使用str(将str 转换为xvalue)。

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 2016-10-24
    • 2013-03-05
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    相关资源
    最近更新 更多