当对数组使用auto时,为什么将其转换为指针而不是引用? [英] When auto is used against array, why it's converted to pointer and not reference?
问题描述
请参见以下示例:
int arr[10];
int *p = arr; // 1st valid choice
int (&r)[10] = arr; // 2nd valid choice
现在,当我们对 arr
使用 auto
时,它将选择第一个选择.
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 ?
推荐答案
是.在该表达式中,由于 lvalue-to-rvalue
转换,该数组衰减为指针类型.
Yes. In that expression, the array decays into pointer type, due to lvalue-to-rvalue
conversion.
如果要使用 array 类型,而不是 pointer 类型,请执行以下操作:
If you want array type , not pointer type, then do this:
auto & x = arr; //now it doesn't decay into pointer type!
目标类型中的
&
可以防止数组衰减为指针类型!
&
in the target type prevents the array from decaying into pointer type!
x
是一个数组,而不是一个指针,可以证明为:
x
is an array and not a pointer, can be proved as:
void f(int (&a)[10])
{
std::cout << "f() is called. that means, x is an array!" << std::endl;
}
int main() {
int arr[10];
auto & x = arr;
f(x); //okay iff x is an int array of size 10, else compilation error!
}
输出:
f() is called. that means, x is an array!
ideone上的演示: http://www.ideone.com/L2Ifp
Demo at ideone : http://www.ideone.com/L2Ifp
请注意,不能使用 pointer 类型调用 f
.可以使用大小为 10
的 int
数组来调用它.尝试使用任何其他类型调用它,将导致编译错误.
Note that f
cannot be called with pointer type. It can be called with an int
array of size 10
. Attempting to call it with any other type, will result in compilation error.
这篇关于当对数组使用auto时,为什么将其转换为指针而不是引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!