C++ 常量引用生命周期(容器适配器)

标签 c++ reference constants lifetime

我的代码如下所示:

class T {};

class container {
 const T &first, T &second;
 container(const T&first, const T & second);
};

class adapter : T {};

container(adapter(), adapter());

我认为常量引用的生命周期就是容器的生命周期。 但是,如果不是这样,适配器对象在容器创建后被销毁,留下悬空引用。

什么是正确的生命周期?

适配器临时对象的堆栈范围是容器对象的范围还是容器构造函数的范围?

如何正确实现绑定(bind)临时对象到类成员引用?

谢谢

最佳答案

根据 C++03 标准,临时绑定(bind)到引用具有不同的生命周期,具体取决于上下文。在您的示例中,我认为下面突出显示的部分适用(12.2/5“临时对象”):

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.

因此,虽然绑定(bind)临时对象是一种延长临时对象 (GotW #88: A Candidate For the "Most Important const") 生命周期的高级技术,但在这种情况下它显然对您没有帮助。

另一方面,Eric Niebler 有一篇您可能感兴趣的文章,其中讨论了一种有趣的(如果令人费解的)技术,该技术可以让您的类的构造函数推断是否已将临时对象(实际上是右值)传递给它(因此必须被复制)或传递的非临时(左值)(因此可能安全地隐藏引用而不是复制):

不过祝你好运 - 每次我阅读这篇文章时,我都必须像以前从未见过这些 Material 一样仔细研究所有内容。它只在我身边短暂停留......

我应该提到 C++0x 的右值引用应该使 Niebler 的技术变得不必要。计划在一周左右发布的 MSVC 2010 将支持右值引用(如果我没记错的话,是 2010 年 4 月 12 日)。不知道 GCC 中右值引用的状态是什么。

关于C++ 常量引用生命周期(容器适配器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2604206/

相关文章:

c++ - 如何在 Xcode 中将 C++ 转换为 Objective C 以编译 Box2D?

java - 是否有类似 C 的方法从 Java 中的枚举中获取项目编号?

c++ - 以某种方式在 C++ 中错误地使用互斥锁

c++ - 如何从 argv[] 获取元素

c++ - 进程启动后立即调试

c++ - 将 Eigen 对象作为参数传递时的指针与引用差异

c++ - 为什么这段代码不起作用? (原型(prototype)中的 &array)

c++ - 指针变量和引用变量有什么区别?

java - 在获取魔术常量的值方面,什么更实用?

tree - Prolog 树遍历