const双指针参数的非const指针参数

leg*_*s2k 6 c++ pointers const function type-conversion

constC++中前星形修改意味着使用该指针值指向不能改变,而指针本身可以由点别的东西.在下面

void justloadme(const int **ptr)
{
    *ptr = new int[5];
}

int main()
{
    int *ptr = NULL;
    justloadme(&ptr);
}
Run Code Online (Sandbox Code Playgroud)

justloadme 函数不应该被允许编辑传递的param所指向的整数值(如果有的话),而它可以编辑int*值(因为const不在第一个星号之后),但是为什么我还是在编译错误时GCC和VC++?

GCC:错误:无效转换int**const int**

VC++:错误C2664:'justloadme':无法将参数1从'int**'转换为'const int**'.转换失去限定符

为什么说转换会失去限定符?是不是获得了const资格赛?而且,它与strlen(const char*)我们传递非const的地方不相似char*

Dav*_*eas 9

大多数情况下,编译器是正确的,直觉是错误的.问题是如果允许那个特定的赋值你可能会破坏程序中的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!!!
Run Code Online (Sandbox Code Playgroud)

标有[*]的行是该违规行为的罪魁祸首,因特殊原因而被禁止.该语言允许将const添加到最后一级但不是第一级:

int * const * correct = &modifier; // ok, this does not break correctness of the code
Run Code Online (Sandbox Code Playgroud)