Why can a non-const reference parameter be bound to a temporary object?

后端 未结 2 2039
难免孤独
难免孤独 2020-12-10 09:03
char f1();
void f2(char&);

struct A {};

A    f3();
void f4(A&);

int main()
{
    f2(f1()); // error C2664. This is as expected.
    f4(f3()); // OK! Why??         


        
相关标签:
2条回答
  • 2020-12-10 09:33

    If you compile with the /Za option to disable language extensions, the compiler rejects both calls:

    > cl /Za test.cpp
    Microsoft (R) C/C++ Optimizing Compiler Version 18.00.21005.1 for x86
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    test.cpp
    test.cpp(11): error C2664: 'void f2(char &)' : cannot convert argument 1 from 'char' to 'char &'
    test.cpp(12): error C2664: 'void f4(A &)' : cannot convert argument 1 from 'A' to 'A &'
            A non-const reference may only be bound to an lvalue
    

    There are several (very constrained) circumstances in which the compiler, with language extensions enabled, will still allow a non-const lvalue reference to bind to an rvalue expression. My understanding is that this is largely to avoid breaking several enormous legacy codebases that rely on this "extension."

    (In general, use of /Za is not recommended for many reasons, but mostly because the Windows SDK headers cannot be #included with the /Za option.)

    0 讨论(0)
  • 2020-12-10 09:41

    You compiler is not standard-compliant (maybe this is documented compiler extension?). GCC gives the following errors:

    main.cpp: In function 'int main()':
    main.cpp:11:11: error: invalid initialization of non-const reference of type 'char&' from an rvalue of type 'char'
        f2(f1()); // error C2664. This is as expected.
            ^
    main.cpp:2:6: error: in passing argument 1 of 'void f2(char&)'
    void f2(char&);
        ^
    main.cpp:12:12: error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'
        f4(f3()); // OK! Why???
                ^
    main.cpp:7:6: error: in passing argument 1 of 'void f4(A&)'
    void f4(A&);
    
    0 讨论(0)
提交回复
热议问题