c++ - 使用 const 引用延长临时对象的生命周期

标签 c++ pass-by-reference lifetime temporary-objects reference-binding

我需要一些关于 const 引用的澄清。 来自 this link :

const Foo &myFoo = FuncBar();

const 引用延长了本地对象的生命周期。但是当我检查 this link尽管他们使用了 const 引用

Sandbox(const string& n) : member(n) {}

字符串“four”的生命周期没有增加。

Sandbox sandbox(string("four"));

他们使用了这句话

Only local const references prolong the lifespan.

那么在第二个链接中,字符串“four”不是主函数的本地字符串吗?const 引用 n 不应该延长其生命周期吗?
那么为什么第二个环节的生命周期没有延长呢?

最佳答案

您引用的两个链接在某种意义上是不同的,一个显示本地常量引用的使用,另一个显示类成员常量引用的使用。

当我们创建本地常量引用并引用临时对象时,编译器会延长临时对象的生命周期,直到本地常量引用的范围。

指向临时对象的类成员常量引用将导致意外结果,因为临时对象的生命周期不会延长到调用初始化类成员引用的构造函数之外。正如答案之一所解释的,临时对象只会存活到构造函数完成为止。

引用以下答案: Does a const reference prolong the life of a temporary?

The lifetime extension is not transitive through a function argument. §12.2/5 [class.temporary]:

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 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 [class.base.init]) persists until the constructor exits. A temporary bound to a reference parameter in a function call (§5.2.2 [expr.call]) persists until the completion of the full expression containing the call.

如果您分析正确,您将意识到在这两种情况下,临时的生命周期都会延长,直到初始化引用的范围有效为止。一旦引用的范围超出范围,临时对象就会变得无效。

对于本地 const 引用,作用域位于函数内部,从该函数内部将其初始化为临时值。 对于类成员 const 引用,范围是构造函数,在该构造函数中将其初始化为临时值。

您还应该阅读这篇 GOTW 文章: https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

关于c++ - 使用 const 引用延长临时对象的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763741/

相关文章:

c++ - 为什么我在传递 vl 或 vl1 时得到与输出相同的值 (0x7fff5fbff808)?地址应该不同

multithreading - 如何将不可变参数传递给线程? (关于终生)

c++ - 返回对 C++ 中可能更改的数据的引用

c++ - 如何从基树类派生

c++ - 支持 IDN 的 URL 解析库

c++ - 如何将函数回调传递给类成员?

c - 如何只交换堆节点的数据

c++ - IShellFolder.EnumObjects - Windows 资源管理器上的异步

rust - 当返回使用 StdinLock 的结果时,为什么保留对 stdin 的借用?

rust - 在 Rust 中正确设置生命周期和可变性期望