Neutrino Neutrino - 16 days ago 6
C++ Question

Assignment to non-const reference

VS2015 Update 3 compiles this with no error and no warning. Yet I was under the impression that temporaries could only be bound to const references. Is this non-conformant or am I misunderstanding something?

struct Foo {};
Foo Func6() { return Foo(); }

TEST(Arguments, NonConstReference)
{
Foo& bob = Func6();
}


EDIT

The question linked by marcinj is the same issue, although that question is not specifically about VS2015 and was not located when I typed this one up.

I had tested using /W4 to see if I got a warning and didn't see one, but testing it again I find that now I do. When opening the project properties to adjust a setting VS2015 has a habit of showing the properties dialog set for a different build configuration than the currently selected one, a most unhelpful behaviour that has caught me out many times, (and will I'm sure continue to do so).

As is mentioned in that other question using Disable Language Extensions (/Za) makes this an error, but is unfortunately not a usable solution as Microsoft's own platform headers won't then compile.

Answer

The MSVC compiler has a non-standard extension, enabled by default, which allows temporaries to bind to non-const references. To disable this, use the command-line option /Za or the corresponding Project Property.