问题
Why is the following illegal?
extern const int size = 1024;
int * const ptr = &size;
Surely a pointer to non-const data should be allowed to point to a const int (just not the other way around)?
This is from C++ Gotchas item #18
回答1:
If you really meant one of
const int * const ptr = &size;
const int * ptr = &size;
that is legal. Yours is illegal. Because it it wasn't you could do
int * ptr const = &size;
*ptr = 42;
and bah, your const was just changed.
Let's see the other way around:
int i = 1234; // mutable
const int * ptr = &i; // allowed: forming more const-qualified pointer
*i = 42; // will not compile
We can't do harm on this path.
回答2:
If a pointer to nonconst data was allowed to point to a const int, then you could use pointer to change the value of the const int, which would be bad. For example:
int const x = 0;
int * const p = &x;
*p = 42;
printf("%d", x); // would print 42!
Fortunately, the above isn't allowed.
来源:https://stackoverflow.com/questions/17392920/assigning-const-int-to-a-const-pointer-to-int-is-illegal