问题
Consider the below code:
#include <iostream>
int func(){
int a = 0;
return a;
}
int main(){
int result = func();
}
According to the cpp standard, some rules about the return statement are:
- A function returns to its caller by the return statement.
- [...] the return statement initializes the glvalue result or prvalue result object of the (explicit or implicit) function call by copy-initialization from the operand
So, the invocation for int result = func();
, as if it could be translate to:
//a fiction code
func(){
int a = 0;
int result = a; #1
}
Because a
is a glvalue, it should be converted to prvalue for prvalue evaluation (initialize an object). So my question is, while invocating int result = func();
in the body of func
, does the glvalue a
which as the operand of return
, need to be converted to a prvalue?
回答1:
Yes a
undergoes lvalue-to-rvalue conversion as part of initializing the result object . (Informally this means the value stored in the memory location named a
is retrieved).
See [dcl.init]/17.8:
Otherwise, the initial value of the object being initialized is the (possibly converted) value of the initializer expression. Standard conversions (Clause 7) will be used, if necessary, to convert the initializer expression to the cv-unqualified version of the destination type; no user-defined conversions are considered.
The Clause 7 includes the lvalue-to-rvalue conversion.
来源:https://stackoverflow.com/questions/61004055/does-lvalue-to-rvalue-conversion-occur-in-function-invocation