tags:

views:

154

answers:

3

I am learning C++ and I found that when a reference is on the right hand side, there can be two cases. Suppose I have a method:

int& GetMe(int& i) { return i; }

And I have:

(1) int j; GetMe(j) = GetMe(i);

and

(2) int& k = GetMe(i);

The consequences of (1) and (2) are different. In (1), the semantic is to copy the value of i into j. The addresses of i and j are remained the same. Changing i doesn't affect j at all. Actually this is the case when you overload the index operator[] and use the index operator for assignment. In (2), the semantic is to create a referent of i as k. k has the same address as i and changing i affects k.

So why do we have the differences? I think, in C++, a reference's address is determined once and only once. Once a reference's address is determined, it can never be changed later. In (1), the reference of j is determined before, so the action is to copy value from i to j. In (2), the reference of k is being declared and initialized so it is done using reference of i. So the action is reference initialization.

I didn't find material explicitly saying above things so I want confirmation. Anyone knows reference well in C++ must can help me or point me to clear material. Thank you very much in advanced.

+2  A: 

In case 1, GetMe returns a reference to j and you then assign a value to j through that reference. In case 2 GetMe returns a reference to i and then you assign that reference to another reference k meaning k refers to i.

References are immutable in C++ (meaning that you cannot change what a reference refers to, though you can change the value of the referent). Reference are also transparently substitutable for what they refer to when used on the right hand side of an expression. The immutability of references means that there is no ambiguity in 1 - you must intend to assign to what the return value of GetMe refers to rather than to change the reference. There is no ambiguity in 2 because you are assigning a reference to a reference (you can't assign an int to a reference to an int).

mattnewport
+3  A: 

What you are missing here is that type of variable is different and it is all that matters. In first example you have int j and in second - int &k.

References in functions prototypes exists in different grounds, they looks the same, underneath they are pretty much the same but they used differently because they exists only when method is executing.

Actually, your code is dong exactly following

int j;
int & j1 = j;
int & i1 = i;
j1 = i1;

versus

int & i1 = i;
int & k = i1;

It's easy to see that in first case two references actually reference different variables i.e. different parts in memory but in second case they all reference the exact same variable. Hence the difference.

vava
A: 

The difference is that in your second example you are defining a reference and in the first example, you are assigning to an existing reference.

R Samuel Klatchko