函数调用中是否发生左值到右值的转换?
Does Lvalue-to-Rvalue conversion occur in function invocation?
考虑以下代码:
#include <iostream>
int func(){
int a = 0;
return a;
}
int main(){
int result = func();
}
根据cpp标准,关于return语句的一些规则是:
- 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
因此,int result = func();
的调用就好像可以转换为:
//a fiction code
func(){
int a = 0;
int result = a; #1
}
因为a
是一个glvalue,所以应该将它转换为prvalue来进行prvalue评估(初始化一个对象)。所以我的问题是,在 func
的主体中调用 int result = func();
时,作为 return
的操作数的泛左值 a
是否需要转换为纯右值?
是 a
在初始化结果对象的过程中进行了左值到右值的转换。 (非正式地,这意味着检索存储在名为 a
的内存位置中的值)。
参见 [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.
第 7 条包括左值到右值的转换。
考虑以下代码:
#include <iostream>
int func(){
int a = 0;
return a;
}
int main(){
int result = func();
}
根据cpp标准,关于return语句的一些规则是:
- 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
因此,int result = func();
的调用就好像可以转换为:
//a fiction code
func(){
int a = 0;
int result = a; #1
}
因为a
是一个glvalue,所以应该将它转换为prvalue来进行prvalue评估(初始化一个对象)。所以我的问题是,在 func
的主体中调用 int result = func();
时,作为 return
的操作数的泛左值 a
是否需要转换为纯右值?
是 a
在初始化结果对象的过程中进行了左值到右值的转换。 (非正式地,这意味着检索存储在名为 a
的内存位置中的值)。
参见 [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.
第 7 条包括左值到右值的转换。