常量双指针参数的非常量指针参数
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
相关文章