Question

In the C++ standard you can read that (8.5.3.2 pag.202)

"A reference cannot be changed to refer to another object after initialization."

but what about the following code

#include <iostream>
#include <functional>

int main(int argc, const char * argv[])
{
    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;

    return 0;
}

that produces this output

j = 3, i = 3

is it realy wrong? is a compiler's "feature" or a C++ language's "feature"? I compiled this code's fragment either on mac (LLVM 5.1) and windows (VS2010).

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top