Does a const reference class member prolong the life of a temporary?(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;
}
给出输出:
答案是:
代替:
答案是:四个
推荐答案
只有 local const 引用才能延长寿命.
Only local const references prolong the lifespan.
标准在第 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 引用类成员是否会延长临时对象的寿命?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:const 引用类成员是否会延长临时对象的寿命?
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
