auto&&; 是什么意思?做?
这是 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(换行符)5
然后我将第 8 行修改为 auto&& a1 = x;
,然后运行。相同的输出。
我的问题:auto&
等于 auto&&
吗?
如果它们不同,auto&&
会做什么?
This is the code from C++11 Notes Sample by Scott Meyers,
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&&
I am having trouble understanding auto&&
.
I have some understanding of auto
, from which I would say that auto& a1 = x
should make type of a1
as int&
Which from Quoted code, seems wrong.
I wrote this small code, and ran under gcc.
#include <iostream>
using namespace std;
int main()
{
int x = 4;
auto& a1 = x; //line 8
cout << a1 << endl;
++a1;
cout << x;
return 0;
}
Output = 4 (newline) 5
Then I modified line 8 as auto&& a1 = x;
, and ran. Same output.
My question : Is auto&
equal to auto&&
?
If they are different what does auto&&
do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
代码是对的。
自动&& p = expr
表示p
的类型为T&&
,其中T
将从expr
推断出来代码>.这里的&&
表示右值引用,因此eg会推断
T == int
,因此p
的类型是int&&
.但是,引用可以根据以下规则折叠:(
此功能用于在 C++11 中实现完美转发。)
情况下
在
x
为左值的 ,不能将右值引用绑定到它,但如果我们推断T = int&
那么p
的类型将变成int& && = int&
,这是一个左值引用,可以绑定到x
。仅在这种情况下,auto&&
和auto&
给出相同的结果。但这两者是不同的,例如,这是不正确的,因为 std::move(x) 是右值,并且左值引用无法绑定到它。
请阅读C++ 右值引用解释进行演练。
The code is right.
auto&& p = expr
means the type ofp
isT&&
whereT
will be inferred fromexpr
. The&&
here indicates a rvalue reference, so e.g.will infer
T == int
and thus the type ofp
isint&&
.However, references can be collapsed according to the rule:
(This feature is used to implement perfect forwarding in C++11.)
In the case
as
x
is an lvalue, an rvalue reference cannot be bound to it, but if we inferT = int&
then the type ofp
will becomeint& && = int&
, which is an lvalue reference, which can be bound tox
. Only in this caseauto&&
andauto&
give the same result. These two are different though, e.g.is incorrect because
std::move(x)
is an rvalue, and the lvalue reference cannot be bound to it.Please read C++ Rvalue References Explained for a walk through.