const 双指针参数的非常量指针参数
C++ 中 star 之前的 const 修饰符意味着使用该指针所指向的值无法更改,而指针本身可以指向其他内容。在下面的
void justloadme(const int **ptr)
{
*ptr = new int[5];
}
int main()
{
int *ptr = NULL;
justloadme(&ptr);
}
justloadme 函数中,不应允许编辑传递的参数指向的整数值(如果有),而它可以编辑 int* 值(因为 const 不在第一个星号之后) ,但为什么我在 GCC 和 VC++ 中都会遇到编译器错误?
GCC: 错误:从 int**
到 const int**
的无效转换
VC++: 错误 C2664: 'justloadme ' : 无法将参数 1 从 'int **' 转换为 'const int **'。转换失去限定符
为什么说转换失去限定符?它不是获得了 const 限定符吗?此外,它不是类似于 strlen(const char*)
我们传递一个非 const char*
The const
modifier in C++ before star means that using this pointer the value pointed at cannot be changed, while the pointer itself can be made to point something else. In the below
void justloadme(const int **ptr)
{
*ptr = new int[5];
}
int main()
{
int *ptr = NULL;
justloadme(&ptr);
}
justloadme
function should not be allowed to edit the integer values (if any) pointed by the passed param, while it can edit the int* value (since the const is not after the first star), but still why do I get a compiler error in both GCC and VC++?
GCC: error: invalid conversion from int**
to const int**
VC++: error C2664: 'justloadme' : cannot convert parameter 1 from 'int **' to 'const int **'. Conversion loses qualifiers
Why does it say that the conversion loses qualifiers? Isn't it gaining the const
qualifier? Moreover, isn't it similar to strlen(const char*)
where we pass a non-const char*
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与大多数情况一样,编译器是正确的,而直觉是错误的。问题是,如果允许该特定分配,您可能会破坏程序中的常量正确性:
标有 [*] 的行是该违规的罪魁祸首,并且由于该特定原因而被禁止。该语言允许将 const 添加到最后一层,但不允许添加到第一层:
As most times, the compiler is right and intuition wrong. The problem is that if that particular assignment was allowed you could break const-correctness in your program:
The line marked with [*] is the culprit for that violation, and is disallowed for that particular reason. The language allows adding const to the last level but not the first: