I read in some good C++ tutorial that independent references do exist, and act like aliasing. But… I wonder what it is made for. Why should one want to use aliasing.
Besides, some piece of code that is not clear to me:
int a;
int &ref = a; // independent reference
int b = 19;
ref = b;
cout << a << " " << ref << "\n";
ref--;
cout << a << " " << ref << "\n";
First, ref is a ‘reference’ to a. I understand from second line of code that address for ref (hence the ampershead) is a. Then, integer ref is assigned the value of b (19). First cout returns a and ref, both equal to 19. Why? Isn’t integer a the address for ref? Then, decrements ref, and last cout gives two times 18. a and ref where decremented.
Only strange possible interpretation of mystery: here int& is a type in itself, ‘independent reference to an integer’, and this type means aliasing. Then whatever you do to ref, the same is done to a.
Is that right? But why should one need aliasing?
You are correct. A reference is similar to a const pointer in many regards (e.g. modifying the value of the reference modifies the original) and you cannot bind the reference to anything else but its initial variable, but it cannot be
nulland the syntax of using it is also different (no need for dereferencing (*,->)). Because it is not a pointer, the best description is alias: think of it as a different name for the same variable.Also, if you pass a reference as a function parameter, no copy of the variable is made (like with a pointer and it pointed-to value), and any change to the reference reflects on the original variable.
There are also special rules for const references that allow a temporary value to live beyond its regular lifetime until the const reference it is bound to goes out of scope.