c++ - 在函数调用中是否会发生左值到右值转换?

标签 c++ c++17 language-lawyer

考虑下面的代码:

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

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

  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();的调用就好像可以转换为:

//a fiction code
func(){
   int a = 0;
   int result = a; #1
}

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

最佳答案

a经过lvalue到rvalue的转换,作为初始化结果对象的一部分。 (非正式地,这意味着将检索存储在名为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包括从左值到右值的转换。

关于c++ - 在函数调用中是否会发生左值到右值转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61004055/

相关文章:

c++ - 返回的std::function保留在std::variant的映射中

c++ - 类模板中可见的友元函数名称

c++ - clang 5.0.0 在涉及虚函数的 coliru/godbolt 上的区别

c++ - CMake 和 Dylib : symbol definitions

c++ - 如何使用 unicode 在 C++ 中打印立方米?

c++ - 浮点成员是否保证使用 {} 语法初始化为零?

C++:如何通过初始化列表进行构造?

c++ - 使用公钥 X509 V3 (PKCS7) 使用 AES 128 模式 cbc 加密文件

c++ - 在 CUDA 中实现可变长度(本地)数组的等价物

c++ - 模板模板参数的替换失败