The line
j = std::ref(k);
Has exactly the same effect has
j = k
That is the reference std::ref(k)
is implicitly dereferenced before assignement to k
that is also to i
. So no wonder the behavior you are seeing. As a proof, just change your code as
int i = 1;
int &j = i;
j = 2; // Ok, now i == 2
int k = 3;
j = std::ref(k);
std::cout << "j = " << j << ", i = " << i << std::endl;
k = 5;
std::cout << "j = " << j << ", i = " << i << std::endl;
Then the output is
j = 3, i = 3
j = 3, i = 3
which shows that j
is not a reference to k
. Changing k
doesn't change j
.