int value1{ 5 }; int value2{ 6 }; int &ref{ value1 }; // okay, ref is now an alias for value1 ref = value2; // assigns 6 (the value of value2) to value1 -- does NOT change the reference!
Note that the second statement may not do what you might expect! Instead of changing
ref
to reference variablevalue2
, it assigns the value ofvalue2
tovalue1
.
Why is the value of ref
not changing? If it is an alias of value1
, here value1
is changing, then why doesn't ref
change?
A reference is just an alias . Once a reference has been set to refer to something, it can't be changed to refer to something else. You can logically replace the reference with the thing it is referring to, to understand what operations on the reference are actually doing.
Since ref
is a reference (alias) to value1
, then ref = value2;
is identical to doing value1 = value2;
The assignment is modifying the thing that ref
refers to ( value1
), it is not modifying ref
itself.
Why the value of ref is not changing
Because that is the way the language has been designed. It is not possible to change what a reference is bound to. That is a fundamental feature of what references are.
All operations that are syntactically performed on a reference variable are operations on the referred object.
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.