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

标签 c++ function pointers type-conversion constants

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/

相关文章:

c++ - Windows 7/64 上的 VirtualAllocExNuma 内存访问时间变慢

python - 用斐波那契数列理解递归

c++ - 如何为 lambda 赋值重载 operator=?

c++ - 如何在方法中使用 vector 和结构成员

c++ - 如何指向具有函数重载的函数?

c++ - 错误 C2440 : '=' : cannot convert from 'std::string []' to 'std::string []'

c++ - 使用成员初始值设定项时 gcc 中可能存在的错误

c++ - C++ 的 3D 图形绘图

c - 在C中写入结构双向链表中的字符串

C——指针问题和void方法问题