FAQ 11.04 What happens when a value is assigned to a reference?

The reference remains bound to the same referent, and the value of the referent is changed.

Because a reference is an alias for its referent, anything done to the reference is actually done to the referent. In particular, a reference is an lvalue (an expression that can appear on the left side of an assignment operator) for the referent. Therefore, assigning to a reference changes the referent.

Said another way, a reference is its referent not a copy of the referent nor a pointer to the referent, but the referent itself.

For example, in the following function f(), the first statement changes main()'s i because the formal parameter x is an alias for i. The second statement also changes i (as well as x) because the address of i is stored in y. The third statement does not change i because z is a copy of the original value of i.

 void f(int& x, int* y, int z) throw() {   x = 5;   //main()'s i changed to 5   *y = 6;  //main()'s i changed to 6   z = 7;   //no change to main()'s i } int main() {   int i = 4;   f(i, &i, i); } 


C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net