【问题标题】:non-const pointer argument to a const double pointer parameter常量双指针参数的非常量指针参数
【发布时间】:2011-03-27 04:07:25
【问题描述】:

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

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*),我们传递一个非常量char*

【问题讨论】:

标签: c++ function pointers type-conversion constants


【解决方案1】:

在大多数情况下,编译器是正确的,而直觉是错误的。问题是,如果允许该特定分配,您可能会破坏程序中的 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

【讨论】:

  • 尽管不允许 const 修改惨败是可以接受的,但编译器会这样做。但是使用int * const * correct 甚至不允许我做*ptr = new int[5];。我该怎么办?
  • 问题很可能在于你想做的不是你写的。你想做什么?签名采用const int **,但您传递的是int **,并在函数内部将其视为int **...您真的想要签名中的const吗?
  • 哦,现在我明白了!我试图做的在概念上是错误的,所以是的,你是对的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多