c++ - 当 auto 用于数组时,为什么它被转换为指针而不是引用?

标签 c++ arrays c++11 language-design

请看下面的例子:

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 类型调用。可以使用大小为 10int 数组调用它。尝试用 any 其他类型调用它,将导致编译错误。

关于c++ - 当 auto 用于数组时,为什么它被转换为指针而不是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6443230/

相关文章:

java - 有什么好的方法可以将多维数组转换为 List<List<T>>?

c++ - 为什么libc++的map实现要用这个union?

ruby - array[1..-2] 是什么意思?

python - 查找 numpy 数组中值的位置

c++ - 如何更改 C 函数中参数的地址?

c++ - 初始化非指针类成员

c++ - 将 std::duration 转换为人类可读的时间

c++ - 如何在 C++11 中初始化(通过初始化列表)多维 std::array?

c++ - Objective C 类中的 Boost Matrix 无法编译

C++ While 循环中的 vector 拆分有什么问题