为什么会这样:
#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;
}
给出以下输出:
答案是:
代替:
答案是:四
原文由 Kyle 发布,翻译遵循 CC BY-SA 4.0 许可协议
只有 本地
const
引用可以延长使用寿命。该标准在第 8.5.3⁄5 节 [dcl.init.ref] 中指定了此类行为,这是关于引用声明的初始化程序的部分。您的示例中的引用绑定到构造函数的参数
n
,并且当对象n
绑定超出范围时变得无效。生命周期扩展不能通过函数参数传递。 §12.2⁄5 [class.temporary]: