简体   繁体   中英

Why is a non-const reference to const allowed if first initialised with non-const?

The compiler will, quite understandably, disallow the following:

const int ci = 1000;
int &r = ci;

because that would mean I could attempt to change the value of ci through r, but ci is const.

Why then is the following allowed, which is the same as above except for first assigning a non-const int to r?

int i;
const int ci = 1000;
int &r = i;
r = ci;

If you try to change ci through r, ci will remain the same value. Nevertheless, it is not caught by the compiler, unlike the first example. Is there an explanation for this?

You aren't rebinding r to reference ci . You're assigning the referencee of r ( i ) the value of ci .

In your example r is created as a reference to i . So when you do this:

r = ci;

You assign the value of ci to r and thus to i . You are not changing the value of ci , so everything is fine.

EDIT: You cannot change which object a reference is bound to.

I think you explained it yourself:

If you try to change ci through r, ci will remain the same value.

r (and by consequence, i) contain a copy of the value of ci, not a reference to ci (which is what you were doing in the first example). So the const nature of ci is not affected and the compiler allows it.

int i;
const int ci = 1000;
int &r = i;
r = ci;

The last line has exactly the same effect as

r = 1000;

You may try changing 1000 through r all day long but it will not happen.

The const keyword controls what you can do through that particular variable name. It does not ensure that the underlying data will never change.

So, for example, is is fairly common to have an object which has an internal state that it can modify freely, but to have that object hand out const references or pointers to its internals so that others can't manipulate them directly.

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