gpt4 book ai didi

c++ - const 双指针参数的非常量指针参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:52 25 4
gpt4 key购买 nike

C++中star之前的const修饰符意味着使用这个指针指向的值不能改变,而指针本身可以指向别的东西。在下面

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

int main()
{
int *ptr = NULL;
justloadme(&ptr);
}

juSTLoadme 函数不允许编辑传递的参数指向的整数值(如果有的话),但它可以编辑 int* 值(因为 const 不在第一个星之后) ,但为什么我在 GCC 和 VC++ 中都会遇到编译器错误?

GCC: 错误:从 int**const int**

的无效转换

VC++:错误 C2664:“juSTLoadme”:无法将参数 1 从“int **”转换为“const int **”。转换失去限定符

为什么说转换失去限定符?它不是获得了 const 限定词吗?此外,它不是类似于 strlen(const char*) 我们传递一个非 const char*

最佳答案

大多数时候,编译器是对的,直觉是错的。问题是,如果允许该特定分配,您可能会破坏程序中的常量正确性:

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

关于c++ - const 双指针参数的非常量指针参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3438125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com