c – 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;
}

给出输出:

The answer is:

代替:

The answer is: four

解决方法:

只有本地const引用才能延长使用寿命.

该标准在§8.5.3/ 5 [dcl.init.ref]中指定了这种行为,这是关于参考声明的初始化者的部分.示例中的引用绑定到构造函数的参数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调用临时对象的函数


下一篇:mysql Temporary file write failure.