当 auto 用于数组时,为什么它会转换为指针而不是引用?
请参阅下面的示例:
int arr[10];
int *p = arr; // 1st valid choice
int (&r)[10] = arr; // 2nd valid choice
现在,当我们对 arr
使用 auto
时,它会选择第一个选择。
auto x = arr; // x is equivalent to *p
是否有理由为数组选择指针而不是引用?
See the below example:
int arr[10];
int *p = arr; // 1st valid choice
int (&r)[10] = arr; // 2nd valid choice
Now when we use auto
against arr
then, it chooses the 1st choice.
auto x = arr; // x is equivalent to *p
Is there a reason for choosing a pointer and not reference for array ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。在该表达式中,由于左值到右值的转换,数组衰减为指针类型。
如果您想要 array 类型,而不是 pointer 类型,请执行以下操作:
目标类型中的
&
可以防止数组衰减为指针类型!x
是一个数组而不是指针,可以证明为:Output:
Demo at ideone : http://www.ideone.com/L2Ifp
请注意,
f
不能用指针类型调用。可以使用大小为10
的int
数组来调用它。尝试使用任何其他类型调用它,将导致编译错误。Yes. In that expression, the array decays into pointer type, due to
lvalue-to-rvalue
conversion.If you want array type , not pointer type, then do this:
&
in the target type prevents the array from decaying into pointer type!x
is an array and not a pointer, can be proved as:Output:
Demo at ideone : http://www.ideone.com/L2Ifp
Note that
f
cannot be called with pointer type. It can be called with anint
array of size10
. Attempting to call it with any other type, will result in compilation error.为了提供该行为的标准参考,7.1.6.4 [dcl.spec.auto] 第 6 段内容如下:
所以我们需要看看其他地方,特别是 14.8.2.1 [tmp.deduct.call] 第 2 段:
为了完整起见,4.2 [conv.array ] 第 1 段:
为了逐步完成它,
auto x = arr;
创建一个虚构的函数template; f(P);
并尝试从调用f(arr)
中推导出P
。在这种情况下,A
是10 int 的数组
,并且P
不是引用类型,因此A
变为 < code> 指向 int 的指针 代替。它沿着链向上渗透回到最终类型 x 。所以基本上,它被视为一个指针,因为规则规定它必须如此。这种方式的行为更有用,因为数组是不可分配的。否则,您的
auto x = arr;
将无法编译,而不是做一些有用的事情。To provide a standard reference for the behavior, 7.1.6.4 [dcl.spec.auto] paragraph 6 reads:
So we need to look elsewhere, specifically 14.8.2.1 [tmp.deduct.call] paragraph 2:
For completeness sake, 4.2 [conv.array] paragraph 1:
To step through it,
auto x = arr;
creates an imaginary functiontemplate<typename P> f(P);
and attempts to deduceP
from the callf(arr)
.A
in this case isarray of 10 int
, andP
is not a reference type, soA
becomespointer to int
instead. Which percolates up the chain back into the final type ofx
.So basically, it is treated as a pointer because the rules say it must. The behavior is simply more useful this way, since arrays are not assignable. Otherwise, your
auto x = arr;
would fail to compile rather than do something useful.auto
产生值。它不会产生参考。考虑到这一点,指针就是对数组提供的值的简单转换。auto
produces values. It will not produce references. With this in mind, then the pointer is the trivial conversion to a value that the array offers.对于数组
arr
,表达式arr
本身意味着&arr[0]
。该规则来自C。因此,IMO,自动选择指针。For an array
arr
, the expressionarr
itself means&arr[0]
. This rule comes from C. Therefore, IMO, auto chooses pointer.