星号前面的const
修饰符意味着使用这个指针所指向的值不能被更改,而指针本身可以用来指向其他的东西。在下面
void justloadme(const int **ptr)
{
*ptr = new int[5];
}
int main()
{
int *ptr = NULL;
justloadme(&ptr);
}
不应该允许justloadme
函数编辑传递的param所指向的整数值(如果有的话),而它可以编辑int*值(因为const不是在第一颗星之后),但是为什么在GCC和VC++中都会出现编译器错误呢?
GCC:错误:从int**
到const int**
的无效转换
VC++: error C2664:‘ convert’:无法将参数1从'int **‘转换为'const int **’。转换丢失限定符
为什么它说转换会失去限定符?它不是获得了const
限定符吗?此外,它是否类似于strlen(const char*)
,在那里我们传递一个非const char*
。
发布于 2010-08-08 23:44:20
与大多数情况一样,编译器是正确的,直觉是错误的。问题是,如果允许执行特定的任务,您可能会破坏程序中的const-正确性:
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添加到最后一个级别,但不允许添加第一个级别:
int * const * correct = &modifier; // ok, this does not break correctness of the code
https://stackoverflow.com/questions/3438125
复制相似问题