non-const pointer argument to a const double pointer parameter(常量双指针参数的非常量指针参数)
问题描述
C++中的const
修饰符在star之前意味着使用这个指针不能改变指向的值,而指针本身可以指向别的东西.在下面
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
函数不应该被允许编辑传递的参数指向的整数值(如果有的话),而它可以编辑 int* 值(因为 const 不在第一个星号之后),但为什么我在 GCC 和 VC++ 中都会出现编译器错误?
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: 错误:从 int**
到 const int**
VC++: 错误 C2664: 'justloadme' : 无法将参数 1 从 'int **' 转换为 'const int **'.转换失去限定符
VC++: error C2664: 'justloadme' : cannot convert parameter 1 from 'int **' to 'const int **'. Conversion loses qualifiers
为什么说转换丢失了限定符?它不是获得 const
限定符吗?此外,它不是类似于 strlen(const char*)
我们传递一个非常量 char*
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*
推荐答案
大多数时候,编译器是对的,直觉是错误的.问题是,如果允许该特定分配,您可能会破坏程序中的 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:
const int constant = 10;
int *modifier = 0;
const int ** const_breaker = &modifier; // [*] this is equivalent to your code
*const_breaker = & constant; // no problem, const_breaker points to
// pointer to a constant integer, but...
// we are actually doing: modifer = &constant!!!
*modifier = 5; // ouch!! we are modifying a constant!!!
标有 [*] 的行是该违规的罪魁祸首,并且由于该特定原因而被禁止.该语言允许将 const 添加到最后一级,但不能添加到第一级:
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:
int * const * correct = &modifier; // ok, this does not break correctness of the code
这篇关于常量双指针参数的非常量指针参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:常量双指针参数的非常量指针参数


基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01