When bar
goes out of scope I expect var
to lose the reference value, but when I print it out it correctly gave the initial value assigned to it. Why is this?
#include <iostream>
struct S
{
int const& var;
S(int const& bar = 5) : var(bar)
{}
};
int main()
{
S s;
std::cout << s.var; // 5
}
What makes you think there's no dangling reference here? There is. The behavior of your program is undefined specifically because it produces a dangling reference. The rest is just a specific manifestation of undefined behavior. Just because your reference is dangling does not mean that it will behave in some explicitly "broken" way.
In your case the reference will probably be implemented under the hood as a pointer. That pointer was originally made to point to some temporary memory location, which originally contained value 5
. Later the memory was "officially" released and the reference become "officially" dangling. But the pointer still retained its old value and the memory it was pointing to still retained the value of 5
. So, until someone overwrites that temporary memory or until someone reinitializes the pointer, you should be able to see the "ghost" of that 5
through that dangling reference. That's exactly what you see in your experiment. You can't meaningfully rely on it in your code, of course.
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