Loom
Loom

Reputation: 9996

Foo &foo = Bar() is legal or is it a compiler issue

struct Foo {};
struct Bar : Foo {};

Foo &foo = Bar(); // without const

As it is written in the answers and comments to this question, I cannot assign a rvalue to a reference. However, I can compile this code (MSVC++ 2010) without error or warning. Is it a known problem of my compiler?

Upvotes: 1

Views: 244

Answers (2)

ali_bahoo
ali_bahoo

Reputation: 4873

You are assigning a temporary value to the reference. It is temporary because, here, Bar() acts like a function that returns a Bar instance which will evaporate at the and of the expression scope, which is here the end of line. It is highly dangerous and illegal, because dereferencing the foo creates an undefined behaviour. I have no idea why MSVC++ allows this "feature" which must be a solid error.

With warning level 4 (/W4) you will get

warning C4239: nonstandard extension used : 'initializing' : conversion from 'Bar' to 'Bar &'

You should always write code with warning level 4.
Lastly, @KerrekSB's answer is better than mine, you should choose his' as an answer.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477680

Temporaries do not bind to non-constant references. That's just the way the language is designed.

While there's in principle no technical obstruction to permitting non-constant access to temporaries, that would almost always be poor design, and quite often flat-out logically erroneous, so the standard just doesn't allow it. If you feel the need to modify a temporary, you should rethink why you want to do that.

Upvotes: 10

Related Questions