auto&& 是做什么的?

What does auto&& do?

本文关键字:什么 auto      更新时间:2023-10-16

这是 Scott Meyers 的 C++11 Notes 示例中的代码,

int x;
auto&& a1 = x;             // x is lvalue, so type of a1 is int&
auto&& a2 = std::move(x);  // std::move(x) is rvalue, so type of a2 is int&&

我无法理解auto&&.
我对auto有一些了解,从中我会说auto& a1 = x应该使a1类型成为int&

从引用的代码来看,这似乎是错误的。

我写了这个小代码,并在gcc下运行。

#include <iostream>
using namespace std;
int main()
{
    int x = 4;
    auto& a1 = x;           //line 8
    cout << a1 << endl;
    ++a1;
    cout << x;
    return 0;
}

输出 = 4 (newline) 5
然后我修改了第 8 行作为auto&& a1 = x;,然后运行。相同的输出。

我的问题:auto&等于auto&&吗?
如果它们不同,auto&&做什么?

代码是正确的。 auto&& p = expr表示p的类型T&&,其中将从expr推断出T。这里的&&表示右值引用,例如

auto&& p = 1;

将推断T == int,因此p的类型是int&&

但是,可以根据以下规则折叠引用:

T& &   == T&
T& &&  == T&
T&& &  == T&
T&& && == T&&

(此功能用于在 C++11 中实现完美转发。

在这种情况下

auto&& p = x;

由于x是左值,因此不能绑定右值引用,但是如果我们推断T = int&那么p的类型将变为int& && = int&,这是一个左值引用,可以绑定到x。只有在这种情况下,auto&&auto&给出相同的结果。这两者是不同的,例如

auto& p = std::move(x);

不正确,因为std::move(x)是右值,并且左值引用无法绑定到它。

请阅读C++ 右值参考资料解释 进行演练。