【问题标题】:What does the double ampersand return type mean? [duplicate]双 & 号返回类型是什么意思? [复制]
【发布时间】:2014-10-03 12:03:46
【问题描述】:

我偶然发现了这样的语法:

int&& move(int&& x)
{
    return x;
}

据说std::move函数是这样实现的,但是我不太明白返回类型(&&)到底是什么意思。

我用谷歌搜索了它,但没有得到答案,有人可以向我解释一下吗?

编辑:

我的大部分困惑来自于函数的返回已经是一个右值,所以我不明白 && 可以在那里改变什么。不知道我是否有意义。

【问题讨论】:

  • 双与号就是我们通常所说的rvalue references。
  • && 只是and 的简写。您可以将代码写成int and move (int and x)。
  • 这不是重复的;那里有关于我返回 r 值引用是好事还是坏事的文章。通过关闭这个问题发送给另一个没有提到返回类型的问题,你忽略了你有答案的可能性。
  • @CodyGray:它询问它是什么返回类型。重定向的问题没有提到的东西。

标签: c++ c++11 move ampersand


【解决方案1】:

发件人:http://www.stroustrup.com/C++11FAQ.html#rval

&& 表示“右值引用”。右值引用可以绑定到右值(但不能绑定到左值):

X a;
X f();
X& r1 = a;      // bind r1 to a (an lvalue)
X& r2 = f();    // error: f() is an rvalue; can't bind

X&& rr1 = f();  // fine: bind rr1 to temporary
X&& rr2 = a;    // error: bind a is an lvalue

【讨论】:

    【解决方案2】:

    在这种情况下,移动功能使用所谓的rvalue references - 相对较新的 C++ 功能。 this article 很好地解释了这一点。

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 1970-01-01
      • 2011-01-17
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 2011-11-19
      相关资源
      最近更新 更多