【发布时间】:2012-02-28 02:05:29
【问题描述】:
这是来自 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&&
我无法理解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&& 会做什么?
【问题讨论】:
-
如果 rhs 是左值,我认为
auto&和auto&&是等价的。如果 rhs 是右值,auto&会给你一个错误。 -
auto&&变量与函数模板中的T&&参数含义相同。