什么是类数据成员的生命周期,const引用一个右值? [英] What is the lifetime of the class data member which const reference to a rvalue?
问题描述
一般来说,此讨论仅限于本地函数变量:
Generally this discussion is up to the local function variable only:
void foo (const int &i)
{
// use i till foo() ends
}
foo(3);
但是,此规则适用于 class
member也?
But, does this rule applies to the class
member also ?
struct A {
const int &a;
A () : a(3) {} // version 1
A (const int &i) : a(i) {} // version 2
};
现在 A
用作
{
return ()? new A : new A(3) : new A(some_local_variable);
}
a 新
分配的整个生命周期内 A
Will the contents of a
remain same through out the life time of the all 3 new
ly allocated A
?
推荐答案
C ++ 03标准12.2 / 5临时对象部分)适当地回答了您的问题:
The C++03 standard (Section "12.2/5 Temporary objects") answers your question aptly:
引用绑定的临时文件或临时文件complete对象绑定到其临时绑定的子对象将持续参考的生命周期,除非下面指定。 在构造函数的ctor-initializer(12.6.2)中临时绑定到引用成员,直到构造函数退出。在函数调用(5.2.2)中,引用参数的临时绑定将持续到包含调用的完整表达式完成。
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) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.
这篇关于什么是类数据成员的生命周期,const引用一个右值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!