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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With