1

My understanding was that references, once assigned, could not be reassigned after. However, in A Tour of C++, Stroustrup has this bit of code:

int x = 2;
int y = 3;
int& r = x;
int& r2 = y;
r = r2;

This seems to imply that the reference r can be reassigned after its initial assignment. Is the rule just that references can only be reassigned to other references or is there something else I'm missing?

iducam
  • 67
  • 1
  • 11
  • 3
    Related: [Can we reassign the reference in C++?](https://stackoverflow.com/questions/9293674/can-we-reassign-the-reference-in-c) – dxiv Mar 09 '21 at 05:52

2 Answers2

2

No there is no reassignment for the references here. Just the value of y which is referenced by r2 is assigned to x which is referenced by r.

To handle this situation, think of the reference as an alias of the variable it references. when you put the reference anywhere you are putting the variable itself.

You can make sure of that by the following code

#include <iostream>

int main()
{
    int x = 2;
    int y = 3;
    int& r = x;
    int& r2 = y;
    r = r2;
    std::cout << std::boolalpha << (&x == &r) && (&y == &r2) && (&y != &r);// gives true
}

Demo

asmmo
  • 6,922
  • 1
  • 11
  • 25
1

You haven't changed what anything is referencing.

If you look at the address of those 4 variables, you will see that:

  • x and r still have the same address.
  • y and r2 still have the same address.
  • x and y still have different addresses.
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173