关于何时返回类型是引用的规则是什么 [英] what are rules about when the return type is reference
问题描述
#include <iostream>
int func0(){
int a = 0;
return a;
}
int&& func1(){
int a = 0;
return a;
}
int main(){
int&& result0 = func0();
int&& result1 = func1();
}
return statement
规则是:
- 函数通过return语句返回其调用者.
- [...] return语句通过从操作数中进行复制初始化来初始化(显式或隐式)函数调用的 glvalue结果或prvalue结果对象.
- 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.
关于如何初始化函数调用对象的规则只有#2.
The rule about how to initialize the object of the function call is only #2.
我们知道表达式func0()
是prvalue.引用result0
需要绑定一个对象,因此temporary materialization conversion
必须将prvalue转换为一个xvalue,因此从prc5的操作数初始化作为prvalue结果对象的临时对象,然后引用reusult0
绑定到临时对象.
We know the expression func0()
is a prvalue. The reference result0
need to bind an object, so temporary materialization conversion
shall covert the prvalue to an xvalue, So the temporary object as the prvalue result object is initialized from the operand of return
, then the reference reusult0
bind to the temporary object.
但是我们知道result1
是引用,并且func1
的返回类型也是引用.对于这种情况, [stmt.return] 不能明确涵盖这种情况,因为result1
是引用而不是object
(glvalue reuslt对象和prvalue结果对象都不是),所以规则是什么关于这个案子?如果我错过了什么,请纠正我.
But we know the result1
is a reference and the return type of func1
is also reference. For this case, [stmt.return] does not clearly cover this case, because result1
is a reference rather than object
(neither glvalue reuslt object nor prvalue result object), so what the rules about this case? If I miss something, please correct me.
推荐答案
您对result0
的分析是正确的.
但是在result1
案例中没有临时实现. "glvalue结果"是通过从操作数a
进行复制初始化而初始化的引用,并且对相同类型的引用进行复制初始化意味着该引用直接绑定(dcl.init.ref/5,通过dcl.init /17.2).然后result1
绑定到glvalue结果.
But there's no temporary materialization in the result1
case. The "glvalue result" is a reference initialized by copy-initialization from the operand a
, and copy-initialization of a reference to the same type means that the reference binds directly (dcl.init.ref/5, via dcl.init/17.2). Then result1
binds to the glvalue result.
这将创建一个悬空的参考;生存期扩展规则(class.temporary/6.2)中明确排除了return
语句.
This creates a dangling reference; a return
statement is explicitly excluded from the lifetime extension rules (class.temporary/6.2).
在int result2 = func1();
的情况下,glvalue结果(一个引用)与结果对象result2
进行了左值到右值的转换,这导致不确定的行为,因为glvalue结果是悬空的.
In the case int result2 = func1();
then the glvalue result (a reference) undergoes lvalue-to-rvalue conversion with result object result2
, this causes undefined behaviour since the glvalue result was dangling.
这篇关于关于何时返回类型是引用的规则是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!