Search code examples
c++visual-c++referencevisual-c++-2010

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?


Solution

  • 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.