Matt Taylor said:
I was a bit surprised when my compiler (both GCC 3.2 & MSVC 7.1)
griped about this piece of code:
int i;
int *p1 = &i;
const int **p2 = &p1; // Invalid type conversion here
I was curious as to why this is so. I don't understand how it would
be wrong to convert an int ** into a const int **. Thanks in advance!
-Matt
This is a non-obvious language restriction designed to stop people from
getting around const specifiers by using indirection. In your example, i is
not const, so presumably there is no objection to it being modified by using
indirection. Nevertheless, the language restriction is motivated by concerns
about modifying const objects.
Suppose that there was an automatic conversion from int ** to const int **
and suppose that there was another variable j, which was a const int.
const int j=2;
int i;
int *p1 = &i;
const int ** p2 = &p1;
Consider p2. Since it is typed as a "pointer to a pointer to const int",
dereferencing it must give the type "pointer to const int". Accordingly,
there is no conversion required in
*p2 = &j;
But p2 points to p1, so this last line has the effect of assigning the
address of j to p1, i.e., it has the effect of
p1 = &j;
Now, since p1 is a pointer to non-const int, the following must be legal
*p1 = 5;
Since p1 points to j, this last line has the effect of assigning 5 to j,
i.e.,
j = 5;
Thus a const object has been modified by using indirection.