我试图了解类型衰减的本质。例如,我们都知道数组在特定上下文中衰减为指针。我的尝试是了解 int[]
如何等同于 int*
但二维数组如何与预期的指针类型不对应。这是一个测试用例:
std::is_same<int*, std::decay<int[]>::type>::value; // true
这会按预期返回 true,但不会:
std::is_same<int**, std::decay<int[][1]>::type>::value; // false
为什么这不是真的?我终于找到了让它返回 true 的方法,那就是将第一个维度设为指针:
std::is_same<int**, std::decay<int*[]>::type>::value; // true
该断言适用于任何带有指针但最后一个是数组的类型。例如 (int***[] == int****;//true
)。
我能解释一下为什么会这样吗?为什么数组类型与预期的指针类型不对应?
最佳答案
Why does
int*[]
decay intoint**
but notint[][]
?
因为用它做指针运算是不可能的。
例如,int p[5][4]
表示一个数组(length-4 array of int
)。不涉及指针,它只是一个大小为 5*4*sizeof(int)
的连续内存块。当您要求特定元素时,例如int a = p[i][j]
,编译器真的是这样做的:
char *tmp = (char *)p // Work in units of bytes (char)
+ i * sizeof(int[4]) // Offset for outer dimension (int[4] is a type)
+ j * sizeof(int); // Offset for inner dimension
int a = *(int *)tmp; // Back to the contained type, and dereference
显然,它只能这样做,因为它知道“内部”维度的大小。转换为 int (*)[4]
保留此信息;它是一个指向(长度为 4 的 int
数组)的指针。然而,一个 int **
不;它只是一个指向(指向 int
的指针)的指针。
有关此问题的另一种看法,请参阅 C 常见问题解答的以下部分:
- 6.18: My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer.
- 6.19: How do I write functions which accept two-dimensional arrays when the width is not known at compile time?
- 6.20: How can I use statically- and dynamically-allocated multidimensional arrays interchangeably when passing them to functions?
(这都是针对 C 的,但这种行为在 C++ 中基本不变。)
关于c++ - 为什么 int*[] 衰减为 int** 而不是 int[][]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14183546/