const引用是否延长了临时的生命?

编程入门 行业动态 更新时间:2024-10-28 15:27:01
本文介绍了const引用是否延长了临时的生命?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么:

#include <string> #include <iostream> using namespace std; class Sandbox { public: Sandbox(const string& n) : member(n) {} const string& member; }; int main() { Sandbox sandbox(string("four")); cout << "The answer is: " << sandbox.member << endl; return 0; }

输出:

答案是:

The answer is:

而不是:

答案是:四个

The answer is: four

推荐答案

只有 local const 可延长寿命。

8.5.3 / 5,[dcl.init.ref],关于参考声明初始化器的部分。在你的例子中的引用绑定到构造函数的参数 n ,并且当对象 n 超出范围。

The standard specifies such behavior in §8.5.3/5, [dcl.init.ref], the section on initializers of reference declarations. The reference in your example is bound to the constructor's argument n, and becomes invalid when the object n is bound to goes out of scope.

生存期扩展不能通过函数参数传递。 §12.2/ 5 [class.temporary]:

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

第二个上下文是当引用绑定到临时时。引用绑定到的临时或临时,即临时绑定的子对象的完整对象将在引用的生存期内保持,除非下面指定。在构造函数的ctor-initializer(§12.6.2[class.base.init])中临时绑定到引用成员,直到构造函数退出。在函数调用中的引用参数的临时绑定(§5.2.2[expr.call])一直持续到包含调用的完整表达式完成。

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引用是否延长了临时的生命?

本文发布于:2023-07-30 16:16:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:生命   const

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!