What I used to know about c++ references is that:
- The reference should be initialized in the declaration statement
- The reference cannot be re-defined once defined
The following piece of code perfectly run on g++ 4.6.1, although it breaks #2:
int a = 10, b = 30;
int& x = a;
x = b;
Jedi mindtrick:
What helped me better understand references is to think of them as names for your variables.
int& x = ajust means that when you sayx, you actually meana.Think of references as an alias.
This is pretty clear:
Think of this not as
x = 10, but as "x is a different name for a".So now,
xwill still referencea, so you give a the value ofb(30).At this point,
xis still bound toa, you just changed its value.So,
x == 30anda == 30at this point, but if you do:xwill also equal10.