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

后端 未结 2 750
慢半拍i
慢半拍i 2020-11-22 05:08

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:



        
相关标签:
2条回答
  • 2020-11-22 05:33

    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.

    0 讨论(0)
  • 2020-11-22 05:43

    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:

    0 讨论(0)
提交回复
热议问题