注意:我使用的是 g++ 编译器(我听说它非常好,应该非常接近标准)。
假设你声明了一个整数数组:
int a[3] = { 4, 5, 6 };
现在假设您真的想声明对该数组的引用(别管为什么,除了 Bjarne 说该语言支持它)。
案例 1 -- 如果你尝试:
int*& ra = a;
然后编译器犹豫并说:
"invalid initialization of non-const reference of type `int*&' from a temporary of type `int*'"
首先,为什么“a”是一个临时变量(即它在内存中没有位置吗?)...
无论如何,很好,每当我看到一个非常量错误时,我都会尝试抛出一个 const...
案例 2 -- 如果你尝试:
int*const&rca = a; //wish I knew where the spaces should go (but my other post asking about this sort of protocol got a negative rank while many of the answers got ranked highly -- aha! there are stupid questions!)
然后一切都很酷,它编译,你得到一个对数组的引用。
Case 3 -- 现在还有一个可以编译的东西:
int* justSomeIntPointer = a; //LINE 1
int*& rpa = justSomeIntPointer; //LINE 2
这也为您提供了对原始数组的引用。
所以这是我的问题:在什么时候静态声明的数组的名称 成为一个常量指针?我似乎记得 int 数组的名称也是一个指向 int 的指针,但我不记得它曾经是一个指向 int 的 const-pointer...
案例 1 似乎失败了,因为声明的引用 (ra) 不是一个 const 指针,这可能意味着“a”一开始就已经是一个 const-pointer-to-int。
情况 2 似乎有效,因为声明的引用 (rca) 已经是一个 const-pointer-to-int。
案例 3 也有效,这很简洁,但为什么呢?假定的指向 int 的指针(即数组名 'a')在什么时候变为 const 指针?是在将它分配给 int* 时发生(第 1 行),还是在将 int* 分配给 int*& 时发生(第 2 行)?
希望这是有道理的。谢谢。
最佳答案
int*& ra = a;
int*
是指针类型,不是数组类型。所以这就是为什么它不会绑定(bind)到 a
,其类型为 int[3]
.
int* const& ra = a;
有效,因为它相当于
int* const& ra = (int*)a;
也就是说,一个临时的指针在概念上被创建在赋值的右边,然后这个临时的被绑定(bind)到ra
。 .所以最后,这并不比:
int* ra = a;
在哪里 ra
实际上是指向数组第一个元素的指针,而不是对数组的引用。
以简单的方式声明对数组的引用:
typedef int array_type[3];
array_type& ra = a;
不那么简单的方法:
int (&ra)[3] = a;
C++11 简单的方法:
auto& ra = a;
At what point does the name of a statically declared array become a const-pointer? I seem to remember that the name of an array of ints is also a pointer-to-int, but I don't remember it ever being a const-pointer-to-int...
这是一个正确的问题!如果您了解何时发生数组到指针的衰减,那么您就是安全的。简单来说有两点需要考虑:
- 尝试任何类型的“复制”时都会发生衰减(因为 C 不允许直接复制数组)
- 衰减是一种转换,在允许转换的任何时候都可能发生:当类型不匹配时
第一种通常发生在模板中。所以给定template<typename T> pass_by_value(T);
,然后 pass_by_value(a)
实际上会通过 int*
, 因为 int[3]
类型的数组无法复制。
至于第二个,您已经看到了它的实际效果:这发生在您的第二种情况下,int* const&
无法绑定(bind)到 int[3]
, 但可以绑定(bind)到临时 int*
,因此发生了转换。
关于c++ - 声明对 Ints 数组的引用时,为什么它必须是对 const 指针的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6827610/