Maestro
Maestro

Reputation: 2552

reference initialization from a temporary object's member data issue

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

}

Upvotes: 0

Views: 50

Answers (2)

Sowmya
Sowmya

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

eerorika
eerorika

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

Related Questions