通过引用临时传递功能的生命周期
我可以做这样的事情:
const int &i = 5;
,并将临时项的生存期延长到 i
的生存期.
and have the lifetime of the temporary extended to the lifetime of i
.
但是
const int &fun (const int &i){
return i;
}
int main () {
const int &r = fun(5);
// Can I use r here?
}
proxy-5的寿命是否仍在延长?还是 r
是一个悬而未决的参考书?
Is the lifetime of the proxy-5 still extended? Or is r
a dangling reference?
这是一个悬而未决的参考.来自[class.temporary]/4-5:
It's a dangling reference. From [class.temporary]/4-5:
在两个上下文中,临时变量在与全表达式结尾不同的时间点被销毁.第一个上下文是将默认构造函数称为[...]
There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when a default constructor is called [ ... ]
第二个上下文是将引用绑定到临时项时.引用所在的临时目录绑定或作为引用所绑定的子对象的完整对象的临时对象仍然存在在参考书的有效期内,除了:
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 of a subobject to which the reference is bound persists for the lifetime of the reference except:
- 与构造函数的 ctor-initializer [...] 中的参考成员的临时绑定
- 在函数调用(5.2.2)中临时绑定到参考参数的会持续到,直到完成包含通话的完整表达式.
- [...]
5
一直持续到包含调用的完整表达式完成为止,即:
The 5
persists until the completion of the full-expression containing the call, which is to say:
const int &r = fun(5);
// <== no more 5