references in c++ problem
I heard references in c++ can be intitalized only once but this is giving me 1 is my output and not returning any error!
struct f {
f(int& g) : h(g) {
h = 1;
}
~f() {
h = 2;
}
int& h;
};
int i() {
int j = 3;
f k(开发者_运维知识库j);
return j;
}
The destructor of f is called after the return value j is captured.
You might want something like this, if you wanted j to be 2:
int i( )
{
int j=3;
{
f k(j);
}
return j;
}
See C++ destructor & function call order for a more detailed description of the order of destruction and the return statement.
You are still initializing the reference only once; assignment and initialization are not the same. The initialization sets up h
so that it references j
(which you never change). Your assignment merely changes the value of j
which is the same as h
, but does not cause h
to refer to a different variable.
I hope this code is only to display the issue, storing a reference to a variable defined outside of the class is very dangerous as your class doesn't have any control over (or knowlege of) when the referenced variable goes out of scope.
精彩评论