在函数调用中是否会发生左值到右值转换? [英] Does Lvalue-to-Rvalue conversion occur in function invocation?

查看:46
本文介绍了在函数调用中是否会发生左值到右值转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

#include <iostream>
int func(){
   int a = 0;
   return a;
}
int main(){
   int result = func();
}

根据cpp标准,关于return语句的一些规则是:

According to the cpp standard, some rules about the return statement are:

  1. 函数通过return语句返回其调用者.
  2. [...] return语句通过操作数中的复制初始化来初始化(显式或隐式)函数调用的glvalue结果或prvalue结果对象/li>
  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

因此,对 int result = func(); 的调用,好像可以转换为:

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
}

由于 a 是glvalue,因此应将其转换为prvalue以进行prvalue评估(初始化对象).所以我的问题是,当在 func 的主体中调用 int result = func(); 时,会做glvalue a 作为操作数 return ,需要转换为prvalue吗?

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?

推荐答案

是的 a 进行从左值到右值的转换,作为初始化结果对象的一部分.(非正式地,这意味着检索存储在名为 a 的存储位置中的值).

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).

请参阅[dcl.init]/17.8:

See [dcl.init]/17.8:

否则,要初始化的对象的初始值为初始化器表达式的(可能是转换的)值.如有必要,将使用标准转换(第7章)将初始化程序表达式转换为目标类型的cv不合格版本.没有考虑用户定义的转换.

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章包含从左值到右值的转换.

The Clause 7 includes the lvalue-to-rvalue conversion.

这篇关于在函数调用中是否会发生左值到右值转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆