While this compiles:
char* p2c;
const char* p2cc = p2c; //fine
because lhs pointed type has all the qualifiers of rhs pointed type, this does not:
char** p2p2c;
const char** p2p2cc = p2p2c; //fail
but this does:
const char * const * p2cp2cc = p2p2c; //fine
Why exactly does this happen?
This does not work:
char** p2p2c;
const char** p2p2cc = p2p2c; //fail
If that was allowed you would be allowed to break const-correctness:
const int k = 10;
int *p;
int **pp = &p;
int const **kpp = pp; // Should this be allowed, if so:
*kpp = &k; // fine, kpp promises not to change it
// yet this does p = &k;
// p made no such promise! this is a hidden const_cast!
*p = 5;
If the assignment was allowed, you would enable setting a non-const pointer (intermediate) to refer to a constant value, possibly causing undefined behavior in a non-obvious to see way. By disallowing that operation the type system is safer.
but this does:
const char * const * p2cp2cc = p2p2c; //fine
This is fine, since the intermediate pointer is fixed, it is impossible to reset the intermediate pointer to refer to a const object and break const-correctness
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With