gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:30:54 25 4
gpt4 key购买 nike

为什么会这样:

#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

最佳答案

仅限本地 const引用延长生命周期。

该标准在第 8.5.3/5 节 [dcl.init.ref] 中指定了此类行为,这是关于引用声明的初始化程序的部分。您示例中的引用绑定(bind)到构造函数的参数 n ,当对象 n 时变为无效必然会超出范围。

生命周期扩展不能通过函数参数传递。 §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/62313021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com