const 引用右值的类数据成员的生命周期是多少?
一般来说,这个讨论仅取决于局部函数变量:
void foo (const int &i)
{
// use i till foo() ends
}
foo(3);
但是,这个规则也适用于class
成员吗?
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
在的整个生命周期内保持不变吗?所有 3 个新分配的
A
?
Generally this discussion is up to the local function variable only:
void foo (const int &i)
{
// use i till foo() ends
}
foo(3);
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
};
Now A
used as,
{
return ()? new A : new A(3) : new A(some_local_variable);
}
Will the contents of a
remain same through out the life time of the all 3 new
ly allocated A
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++03 标准(第“12.2/5 临时对象”)恰当地回答了您的问题:
引用绑定到的临时对象或作为子对象的完整对象的临时对象其中临时绑定在引用的生命周期内持续存在,除非下面指定。 构造函数构造函数初始化程序 (12.6.2) 中引用成员的临时绑定将持续存在,直到构造函数退出。函数调用 (5.2.2) 中对引用参数的临时绑定将持续存在,直到包含调用的完整表达式完成为止。
The C++03 standard (Section "12.2/5 Temporary objects") answers your question aptly:
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.
如果您使用
new
分配一个对象,它将永远保留在内存中 - 直到您删除
它。它不是一个临时对象。a
是A
的成员,也是分配的一部分。编辑:感谢您的评论。我想说 - 不,这是不正确的。考虑一下:
如果
A
对象的生命周期跨越多个函数,答案就更明显。旁注:我发现“内容”这个词在这里有点含糊。将引用等同于指针,因此您的
a
基本上指向一个整数。不管是否为 const,如果该整数不再存在(因为它在堆栈上并且已被删除),那么您的a
- 虽然仍然指向内存中的相同地址 - 现在正在引用其他内容。 GotW 文章似乎正在谈论编译器延长引用所指向的对象的生命周期。同样,引用本身只是一个指针。If you allocate an object using
new
, it will remain in memory forever - until youdelete
it. It's not a temporary object.a
is a member ofA
, and as such part of the allocation.EDIT: Thanks for the comments. I would say - no, this is not correct. Consider this:
The answer is more obvious if the lifetime of the
A
object spans across several functions.Side note: I find the word "contents" a bit ambiguous here. Equate the reference with a pointer, so your
a
is basically pointing to an integer. const or not, if the integer does no longer exist (because it was on the stack and has been removed), youra
- while still pointing to the same address in memory - is referencing something else now. The GotW article appears to be talking about the compiler prolonging the lifetime of the object being pointed to by the reference. The reference itself, again, is just a pointer.