c++ - Change a variable reference after his initialization -
in c++ standard can read (8.5.3.2 pag.202)
"a reference cannot changed refer object after initialization."
but following code
#include <iostream> #include <functional> int main(int argc, const char * argv[]) { int = 1; int &j = i; j = 2; // ok, == 2 int k = 3; j = std::ref(k); std::cout << "j = " << j << ", = " << << std::endl; return 0; } that produces output
j = 3, = 3 is realy wrong? compiler's "feature" or c++ language's "feature"? compiled code's fragment either on mac (llvm 5.1) , windows (vs2010).
the line
j = std::ref(k); has same effect has
j = k that reference std::ref(k) implicitly dereferenced before assignement k i. no wonder behavior seeing. proof, change code as
int = 1; int &j = i; j = 2; // ok, == 2 int k = 3; j = std::ref(k); std::cout << "j = " << j << ", = " << << std::endl; k = 5; std::cout << "j = " << j << ", = " << << std::endl; then output is
j = 3, = 3 j = 3, = 3 which shows j not reference k. changing k doesn't change j.
Comments
Post a Comment