auto&& 是做什么的?
What does auto&& do?
这是 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++ 右值参考资料解释 进行演练。
相关文章:
- 'for (auto c : str)' c到底是什么?
- 什么是'auto my_var ='与"自动my_var="的沟通?
- 在 Objective-C++ 中应用于__weak指针时,通过关键字推导类型"auto"规则是什么?
- "auto x = vector<int>()"和"vector<int> x"有什么区别?
- 将右值分配给'const auto&'时会发生什么情况
- "auto v = f()"和"auto&& v = f()"有什么区别?
- 使用"auto"进行迭代时,"&"符号有什么作用
- auto&x = const int *的类型是什么?
- 'auto f(params) -> decltype(..., void())' 中的 'void()' 是做什么的?
- auto&& 告诉我们什么?
- 什么时候应该使用 decltype(x) 而不是 auto 来声明变量的类型
- 有什么理由不使用 auto& 进行C++基于范围的 for 循环?
- 这是(auto && elem : v)语法简单C++吗?我应该使用什么编译器来编译它?
- C++11 中的"auto var = {condition} ? 1 : 1.0"是什么类型?是双精度还是整数?
- 使用auto声明变量和使用类型名称之间的区别是什么
- 如果我们使用 "decltype(auto) f()" 作为函数声明,定义中带有"decltype(f()) result",会发生什么?
- auto&& 是做什么的?
- 关于auto作为参数类型,C++14标准有什么规定
- auto在c++ 11中的含义改变;请删除它这是什么意思
- 使用"for(auto&e : cont)"安全吗?矢量有什么问题<bool>?