3

I have the following code on Visual C++ 17 compiler:

#include "stdafx.h"
class Foo {};

Foo FuncBar()
{
    return Foo();
}
int main()
{
    Foo &myFoo = FuncBar();
}

Normally IIRC, assigning temporaries to lvalues should be illegal. Here I am returning a temporary Foo() and binding it to an lvalue ref. However this code compiles and even runs fine. Why is this allowed?

Onur Gumus
  • 1,389
  • 11
  • 27
  • 1
    Because microsoft thinks it's a good idea to allow it... there's not really any other answer – M.M Oct 23 '17 at 08:20
  • @M.M is it documented by Microsoft somewhere ? – Onur Gumus Oct 23 '17 at 08:21
  • They thought Xamarin was a good idea, so credibility is questionable... – DeiDei Oct 23 '17 at 08:21
  • @OnurGumus Yes, have you tried searching their documentation? – M.M Oct 23 '17 at 08:21
  • @M.M I have found the documentation for Microsoft Extensions. But cannot see this specific behavior is documented. But setting /Za certainly "fixes" the issue. – Onur Gumus Oct 23 '17 at 08:24
  • It's an ancient microsoft bug which they like to claim is an "extension". It has remained in every microsoft compiler because seemingly at microsoft, backward compatibility with faulty codebases is more important than correctness. – Richard Hodges Oct 23 '17 at 09:22
  • @RichardHodges /permissive- Fixes the problem – Onur Gumus Oct 23 '17 at 09:54

1 Answers1

0

It is a Microsoft C++ extension. You can make the compilation fail by using the /Za flag.

Jodocus
  • 7,493
  • 1
  • 29
  • 45
  • I've heard that MS recommend not to use /Za for real code as it makes various other things break that shouldn't... – M.M Oct 23 '17 at 08:22
  • Appereantly this is the doc but cannot find this behaviour documented: https://learn.microsoft.com/en-us/cpp/build/reference/microsoft-extensions-to-c-and-cpp – Onur Gumus Oct 23 '17 at 08:23
  • @ M. M Certainly windows.h will not compile any longer. On https://learn.microsoft.com/de-de/cpp/build/reference/za-ze-disable-language-extensions Microsoft suggests that you use this option only if you plan to be portable. – Jodocus Oct 23 '17 at 08:32
  • 2
    The correct switch is to use /permissive- as documented here: https://blogs.msdn.microsoft.com/vcblog/2016/11/16/permissive-switch/ This causes a valid compiler error. /Za is not recommended. – Onur Gumus Oct 23 '17 at 08:49