Does Lvalue-to-Rvalue conversion occur in function invocation?

混江龙づ霸主 提交于 2021-02-05 09:18:45

问题


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:

  1. A function returns to its caller by the return statement.
  2. [...] 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!