问题
I read about C++ reference variables and somewhere I found this:
A declaration of a const reference is redundant since reference can never be made to refer to another object.
what does it mean?
Here, for example, I can change the object that the reference is referring to:
void p(int& i) {
int a = 7,c = 0;
i = a;
}
So what does it mean that "Reference can never be made to refer to another object"?
thanks in advance.
回答1:
It means, given this code
int a;
int b;
int& ref = a;
that, once you've initialized ref to refer to a, there is no way you can make it refer to b or any other variable.
Any change you make to the reference will reflect on the variable that you used to initialize it with. The reference (which itself is not even a proper object) stays intact.
Also, a reference is only usable as long as the object it refers to stays alive.
回答2:
In your example, you are not changing what i is pointing at. It is changing the VALUE of i to the value of a. If you where to display the address of i, you'd see it is different from a.
回答3:
If you do int &r = x; this means that r refers to x and every time you change r, you really change x. Likewise every time you change x that change is visible through r.
Now what "Reference can never be made to refer to another object" means is that once you do int &r =x, you can't make r refer to y. You can do r = y;, but all that does is to set x equal to y. It does not means that changing r afterwards will change y nor does it mean that changes to y will be visible through r.
回答4:
The simplest way to envision it is to speak in terms of pointers:
// reference // equivalent pointer code
int& r = a; int* const r = &a;
r = b; *r = b;
function(r); function(*r);
That is, at the moment of declaration, a reference declares an alias to an existing object's memory location. Then, any use of the reference is equivalent to dereferencing a pointer to that memory location.
Now, what of a const reference ? Well it would be:
// reference // equivalent pointer code
int& const r = a; int* const const r = &a;
int const& const r = a; int const* const const r = &a;
which makes the redundancy quite obvious, I believe.
来源:https://stackoverflow.com/questions/17898110/what-does-reference-can-never-be-made-to-refer-to-another-object-mean