问题描述
我的代码看起来像这样:
I have code that looks like this:
class T {};
class container {
const T &first, T &second;
container(const T&first, const T & second);
};
class adapter : T {};
container(adapter(), adapter());
我认为常量引用的生命周期将是容器的生命周期。
I thought lifetime of constant reference would be lifetime of container.However, it appears otherwise, adapter object is destroyed after container is created, leaving dangling reference.
正确的生命周期是什么?
What is the correct lifetime?
是容器对象或容器构造函数的适配器临时对象的范围?
is stack scope of adapter temporary object the scope of container object or of container constructor?
如何正确实现绑定临时对象到类成员引用?
how to correctly implement binding temporary object to class member reference?
感谢
推荐答案
03标准,与参考的临时绑定具有不同的寿命,具体取决于上下文。在您的示例中,我认为以下突出显示的部分适用(12.2 / 5临时对象):
According to the C++03 standard, a temporary bound to a reference has differing lifetimes depending on the context. In your example, I think the highlighted portion below applies (12.2/5 "Temporary objects"):
所以,绑定临时是一种高级技术来延长临时对象的生命周期(),它显然不会帮助你在这种情况下。
So while binding a temporary is an advanced technique to extend the lifetime of the temporary object (GotW #88: A Candidate For the "Most Important const"), it apparently won't help you in this case.
另一方面,Eric Niebler有一篇文章,你可能会感兴趣,讨论一个有趣的(如果卷积的)技术,可以让你的类的构造函数推断一个临时对象(实际上是一个右值)已经传递给它(因此必须被复制)或非临时(lvalue)被传递(因此可能安全地有一个引用被隐藏而不是复制):
On the other hand, Eric Niebler has an article that you may be interested in that discusses an interesting (if convoluted) technique that could let your class's constructors deduce whether a temporary object (actually an rvalue) has been passed to it (and therefore would have to be copied) or a non-temporary (lvalue) as been passed (and therefore could potentially safely have a reference stashed away instead of copying):
- Conditional Love: FOREACH Redux
祝你好运 - 每次阅读这篇文章时,我都必须努力工作,好像我从来没有见过这些材料。它只会坚持我一个短暂的时刻...
Good luck with it though - every time I read the article, I have to work through everything as if I've never seen the material before. It only sticks with me for a fleeting moment...
我应该提到C ++ 0x的右值引用应该使Niebler的技术不必要。 Rvalue引用将由MSVC 2010支持,计划在一周左右(如果我正确回忆,2010年4月12日)发布。我不知道右值引用的状态是在GCC。
And I should mention that C++0x's rvalue references should make Niebler's techniques unnecessary. Rvalue references will be supported by MSVC 2010 which is scheduled to be released in a week or so (on 12 April 2010 if I recall correctly). I don't know what the status of rvalue references is in GCC.
这篇关于C ++常量引用寿命(容器适配器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!