Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-const pointer argument to a const double pointer parameter

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);
}

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: error: invalid conversion from int** to const int**

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

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*

like image 260
legends2k Avatar asked Aug 09 '10 07:08

legends2k


1 Answers

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!!!

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
like image 70
David Rodríguez - dribeas Avatar answered Sep 20 '22 01:09

David Rodríguez - dribeas