c++ - const 引用类成员是否会延长临时对象的生命周期?

标签 c++ temporary ctor-initializer const-reference

为什么会这样:

#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] 中关于引用声明的初始值设定项的部分中指定了此类行为。您的示例中的引用绑定(bind)到构造函数的参数 n,并且当对象 n 绑定(bind)到超出范围时变得无效。

生命周期延长不能通过函数参数传递。 §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.

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

相关文章:

c++ - 如何在 C++ 中创建一个随机数数组

c++ - 当左值分配给右值引用时会发生什么?没有破坏临时对象?

c++ - 如何在 C++ 中创建临时变量

c++ - 在基类的构造函数中正确初始化 unique_ptr

c++ - 如何初始化类字段?

c++ - 如何像传递未定义函数一样传递未定义方法

c++ - 构造函数和对象成员变量初始化

具有STL容器的c++函数模板特化

phpqrcode - 将文件保存到临时目录

c++ - 我可以调用虚函数来初始化基类子对象吗?