简体   繁体   中英

Why can't I put a pointer to const on right hand side of assignment?

Why can't I put const int *cp1 , on the right hand side of an assignment? Please see this sample

int x1 = 1;
int x2 = 2;

int *p1 = &x1;
int *p2 = &x2;

const int *cp1 = p1;

p2 = p1;    // Compiles fine

p2 = cp1;   //===> Complilation Error

Why do I get error at the indicated location? After all I am not trying to change a constant value, I am only trying to use a constant value.

Am I missing something here.

After all I am not trying to change a constant value

Implicit conversion from "pointer to const" to "pointer to non-const" is not allowed, because it'll make it possible to change a constant value. Think about the following code:

const int x = 1;
const int* cp = &x; // fine
int* p = cp;        // should not be allowed. nor int* p = &x;
*p = 2;             // trying to modify constant (i.e. x) is undefined behaviour

BTW: For your sample code, using const_cast would be fine since cp1 is pointing to non-const variable (ie x1 ) in fact.

p2 = const_cast<int*>(cp1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM