问题
Iv got to the stage in my c++ study concerning references. It states the following rule:
Once a reference is initialized to an object, it cannot be changed to refer to another object.
Iv wrote a short code (as asked to in an exercise) that is meant to prove this rule correct.
int y = 7;
int z = 8;
int&r = y;
r = z;
Can someone explain why this code compiles without any errors or warnings?
回答1:
r = z
does not change what r
"points to." It assigns the value of z
to the object pointed to by r
.
The following code does the same thing as your code, but using pointers instead of references:
int y = 7;
int z = 8;
int* p = &y; // p points to y
*p = z; // assign value of z to the object pointed to by p (which is y)
回答2:
It does not make the reference alias to something else but it changes the value of what r
contains.
int&r = y;
r
is reference to y
r = z;
changes value of y
& r
to value of z
by assigning value of z
to r
& hence y
.
回答3:
int&r = y;
r = z;
It does NOT change the reference. Rather it changes the value pointed to by the reference variable. The reference variable is just yet another name of y
. So r=z
is equivalent to
y = z;
That is, r=z
changes the value of y
.
Reference variable cannot be reset to refer to another variable, in any way.
回答4:
You're not changing the reference; you're setting a new value to the referred object. After this example you should note that y==8.
回答5:
When you do r = z
you are not reseating the reference, instead you are copying the value of z
into y
.
来源:https://stackoverflow.com/questions/6930507/why-does-changing-what-a-reference-points-to-not-throw-an-error