为什么会这样:
#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/