这是一个代码片段,希望能传达我正在尝试做的事情:
void updatePointer(const int*& i)
{
i++;
}
int main() {
int array[5];
int* arrayPtr = array;
updatePointer(arrayPtr );
return 0;
}
这会产生编译错误:
prog.cpp: In function ‘int main()’:
prog.cpp:16: error: invalid initialization of reference of type ‘const int*&’ from
expression of type ‘int*’
prog.cpp:5: error: in passing argument 1 of ‘void updatePointer(const int*&)’
最佳答案
假设你能做到,你可以这样写:
const int c = 0;
void updatePointer(const int* &i) {
i = &c;
}
int main() {
int *ptr;
updatePointer(ptr);
*ptr = 1; // attempt to modify the const object c, undefined behavior
}
const
的目的是确保用户代码不能尝试修改 const 对象,除非它包含 const-cast(或等价物)。所以编译器不得不拒绝这段代码。禁止 const int*&
绑定(bind)到 int*
是上面代码中编译器拒绝合理的唯一地方:其他每一行都可以。
这与您不能将 int**
隐式转换为 const int **
的原因相同。
除了 const-safety 方面的动机之外,您可以考虑是否 int*
是与 const int*
不同的类型,那就是这样恰好可以转换为它。同样,您可以将 int
转换为 double
,但 double&
不能绑定(bind)到 int
左值。这不是全部原因,因为实际上 int*
和 const int*
具有相同的大小和表示,而 int
和 double
不要。因此,如果不是因为它会破坏 const 系统这一事实,可能会有一个允许它的特殊情况。
C++ 对 strchr
同时具有 const 和非 const 重载的原因与此问题有关:您的函数 updatePointer
修改其输入而不是返回更新后的值,但原理是相似的。 C 风格的单个 strchr
允许您将指向 const 的指针“洗白”为指向非常量的指针而无需强制转换,这是 const 系统中的一个漏洞。 C++ (a) 有重载并且 (b) 有比 C 更严格的类型系统,所以它弥补了这个漏洞。
如果您希望您的实际函数 updatePointer
像 strchr
一样工作——检查指向的数据并为指针计算一个新值,那么您就在strchr
的情况相同。这与它对新值的作用无关(在 strchr
的情况下返回它,在 updatePointer
的情况下写回),因为问题是你想要新指针具有与输入相同的 const 限定。您需要提供 const 和非常量重载或函数模板。
如果您只需要真正的函数 updatePointer
将指针移动一定距离,而不考虑指向的数据,则可以使用 std::advance
代替。
关于c++ - 为什么我不能将一个非 const 指针传递给一个以指向 const 的指针作为参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12600094/