Why bind a non-constant reference parameter to a temporary object?

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???
}

error C2664: 'void f4 (char &)': cannot convert argument 1 from 'char' to 'char &'

I was taught that in C ++ a non-constant reference parameter cannot be bound to a temporary object; and in the above code, it f2(f1());triggers an error as expected.

However, why does the same rule not apply to the code line f4(f3());?

PS: My compiler is VC ++ 2013. Even if I comment on the line f2(f1());, then the code containing f4(f3());will be compiled without any errors or warnings.

Update:

MSDN says:

Visual ++ . const.

, , V++. V++

+3
2

/Za , :

> 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

( ) , - -const lvalue rvalue. , , , "".

( /Za , , Windows SDK # /Za.)

+4

(, ?). GCC :

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&);
+2

Source: https://habr.com/ru/post/1621140/


All Articles