Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no dangling reference?

Tags:

c++

reference

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
}
like image 981
Me myself and I Avatar asked Feb 16 '23 10:02

Me myself and I


1 Answers

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.

like image 113
AnT Avatar answered Feb 18 '23 23:02

AnT