[英]Is there a sequence point between return and expression in return statement?
Here is the quote from standard : 这是来自标准的报价:
The second context is when a reference is bound to a temporary.
第二种情况是引用绑定到临时项时。 The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below.
引用所绑定的临时对象或作为与该临时对象所绑定的子对象的完整对象的临时对象在引用的生存期内一直存在,除非以下指定。 A temporary bound to a reference member in a constructor's ctor-initializer (§12.6.2 [class.base.init]) persists until the constructor exits.
在构造函数的ctor-initializer(第12.6.2节[class.base.init])中,绑定到引用成员的临时绑定一直存在,直到构造函数退出。 A temporary bound to a reference parameter in a function call (§5.2.2 [expr.call]) persists until the completion of the full expression containing the call.
在函数调用(第5.2.2节[expr.call])中,绑定到参考参数的临时绑定将一直持续到包含该调用的完整表达式完成为止。
Please look at the code : 请看代码:
#include <iostream>
using namespace std;
struct foo{const char* bar ; foo(): bar("This is foo"){} };
foo returnByValue(){ return foo(); }
const foo& returnByConstRef() { return returnByValue(); }
int main() {
std::cout<< returnByConstRef().bar <<std::endl; // is life of temp is extended in while this expression?
return 0;
}
is the above program valid? 以上程序有效吗? or temp object in the following statement dies before return statement leaves the function?
或以下语句中的临时对象在return语句离开函数之前死亡?
return returnByValue();
if so making the statement 如果是这样的话
const char*& jinjja = returnByConstRef().bar;
is invalid? 是无效的?
The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended;
在函数返回语句(6.6.3)中,临时绑定到返回值的生存期不会延长; the temporary is destroyed at the end of the full-expression in the return statement.
临时在return语句中的全表达式结束时销毁。
This should answer your question. 这应该可以回答您的问题。
It may help to know that when a function returns, the order of events is as follows: 知道一个函数返回时,事件的顺序如下可能会有所帮助:
return
statement (if any). return
语句(如果有)中的表达式初始化。 This initialization, which includes the evaluation of the expression, constitutes a full-expression . return
statement are destroyed (in reverse order of initialization). return
语句中创建的临时文件将被销毁(以相反的顺序进行初始化)。 (This doesn't include the temporary introduced to hold the return value, in the case that the function's return type is not a reference.)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.