auto &&做什么?

Vin*_*arg 35 c++ auto c++11

这是来自Scott Meyers的C++ 11 Notes Sample的代码,

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&&
Run Code Online (Sandbox Code Playgroud)

我理解困难auto&&.
我有一定的了解auto,从中我会说,auto& a1 = x应该使类型a1int&

哪个来自引用代码,似乎有误.

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

#include <iostream>

using namespace std;

int main()
{
    int x = 4;
    auto& a1 = x;           //line 8
    cout << a1 << endl;
    ++a1;
    cout << x;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

我的问题:auto&等于auto&&
如果他们不同的是auto&&什么呢?

ken*_*ytm 43

代码是对的.auto&& p = expr装置的类型p就是T&&其中T将从推断expr.在&&这里表示右值引用,所以如

auto&& p = 1;
Run Code Online (Sandbox Code Playgroud)

将推断T == int并因此的类型pint&&.

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

T& &   == T&
T& &&  == T&
T&& &  == T&
T&& && == T&&
Run Code Online (Sandbox Code Playgroud)

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

在这种情况下

auto&& p = x;
Run Code Online (Sandbox Code Playgroud)

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

auto& p = std::move(x);
Run Code Online (Sandbox Code Playgroud)

是不正确的,因为std::move(x)是一个右值,并且左值引用不能绑定到它.

请阅读C++ Rvalue References Explained for a walk through.