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
这篇关于常量双指针参数的非常量指针参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:常量双指针参数的非常量指针参数


基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01