Non-const reference bound to temporary, Visual Studio bug?

I ran into this while compiling some portable code in gcc. Basically this strange code compiles in Visual studio which really just blows my mind:

class Zebra {int x;};
Zebra goo() {Zebra z; return z;}
void foo(Zebra &x)
{
    Zebra y;
    x = y;
    foo(goo());
}

Visual studio lets this one fly. gcc will catch this as a compile error. Interestingly, If you typedef Zebra to int, VC++ will complain. Quite contradictory behavior. Thoughts?


This is old extension to Visual Studio, the only reference I could find on the Microsoft site was this bug report: Temporary Objects Can be Bound to Non-Const References, which has the following example code:

struct A {};

A     f1();
void f2(A&);

int main()
{
    f2(f1()); // This line SHALL trigger an error, but it can be compiled without any     errors or warnings.
}

One of the responses notes:

There is a level 4 warning (level 4 warning are enabled if you pass /W4 to the compiler) for it

This blog post: Visual C++ is so Liberal which covers this extension notes that:

Using Disable Language Extensions (/Za) makes it an error:


As others said, this is due to Microsoft C++ extension. Though /Za flag is not recommended as it can break things.

Instead use the /permissive- switch for better standards compliancy and you will get healthy errors for these cases. Note that this flag is available since VS 2017.

The switch /Za does not support certain key Microsoft SDK header files. By contrast /permissive- offers a useful conformance mode where input C++ code is interpreted according to ISO C++ rules but also allows conforming extensions necessary to compile C++ on targets supported by Visual C++.

More info is on Visual C++ Team Blog.