非const指针参数到一个const双指针参数

非const指针参数到一个const双指针参数

本文介绍了非const指针参数到一个const双指针参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中的 const 修饰符在星号之前表示使用此指针时,指向的值不能更改,而指针本身可以指向其他值。在下面

The const modifier in C++ before star means that using this pointer the value pointed at cannot be changed, while the pointer itself can be made to point something else. In the below

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

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

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

justloadme function should not be allowed to edit the integer values (if any) pointed by the passed param, while it can edit the int* value (since the const is not after the first star), but still why do I get a compiler error in both GCC and VC++?

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

GCC: error: invalid conversion from int** to const int**

VC ++:错误C2664:'justloadme':无法转换参数1从'int * '到'const int * '。转化失去限定词

VC++: error C2664: 'justloadme' : cannot convert parameter 1 from 'int *' to 'const int *'. Conversion loses qualifiers

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

Why does it say that the conversion loses qualifiers? Isn't it gaining the const qualifier? Moreover, isn't it similar to strlen(const char*) where we pass a non-const char*

推荐答案

大多数时候,编译器是正确的,直觉错了。问题是如果允许这个特定的赋值,你可以破坏程序中的const正确性:

As most times, the compiler is right and intuition wrong. The problem is that if that particular assignment was allowed you could break const-correctness in your program:

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添加到最后一个级别,但不是第一个:

The line marked with [*] is the culprit for that violation, and is disallowed for that particular reason. The language allows adding const to the last level but not the first:

int * const * correct = &modifier; // ok, this does not break correctness of the code

这篇关于非const指针参数到一个const双指针参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:09