本文介绍了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引用会延长寿命.

该标准在第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]:

这篇关于const引用类成员是否可以延长临时对象的寿命?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:10
查看更多