Reputation: 2552
A non-const reference can be bound only to an lvalue so I have tried this:
struct Foo
{
double value = 5.45;
operator double&(){return value;}
};
int main()
{
double& d = Foo{};
cout << d << endl; // seems ok 5.45
}
d
is a reference initialized from an unnamed temporary object Foo{}
's member data value
but that temporary is destroyed at the next semi-colon which means it destroys also its member value
but d
is still referencing it. So why I get the correct value 5.45
? Does my code yield a UB? Is d
a dangling referencing now? please explain Thank you!Upvotes: 0
Views: 50
Reputation: 91
If 'd' is still referencing 'value' and 'd' is a non-const lvalue reference of type 'double&', agree? Then have you tried binding 'd' to an rvalue of type 'double' ?
Upvotes: 0
Reputation: 238351
So why I get the correct value 5.45?
Because the behaviour of the program is undefined.
Does my code yield a UB?
Yes. You access an object outside of its lifetime.
Is d a dangling referencing now?
Yes. As you said: The temporary object along with its member have been destroyed. All previously valid references to the destroyed object have become invalid i.e. dangling.
// seems ok 5.45
It might seem OK, but it is nevertheless not OK.
Upvotes: 2