const引用类成员是否可以延长临时对象的寿命? [英] Does a const reference class member prolong the life of a temporary?

查看:147
本文介绍了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: 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引用类成员是否可以延长临时对象的寿命?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆