请看下面的例子:
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
choosing a pointer and not reference 有什么原因吗?对于数组?
最佳答案
是的。在该表达式中,由于 lvalue-to-rvalue
转换,数组衰减为指针类型。
如果你想要 array 类型,而不是 pointer 类型,那么这样做:
auto & x = arr; //now it doesn't decay into pointer type!
目标类型中的&
防止数组衰减为指针类型!
x
是一个数组而不是一个指针,可以证明为:
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
注意 f
不能 用 pointer 类型调用。可以使用大小为 10
的 int
数组调用它。尝试用 any 其他类型调用它,将导致编译错误。
关于c++ - 当 auto 用于数组时,为什么它被转换为指针而不是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6443230/