从函数返回引用与临时绑定到常量引用

Return reference from function vs binding temporary to const ref

本文关键字:引用 绑定 常量 函数 返回      更新时间:2023-10-16

我是对的,这个(取自这个GotW(:

string f() { return "abc"; }
void g() {
    const string& s = f();
    cout << s << endl;    // can we still use the "temporary" object?
}

完全没问题,而这根本不行:

const string& foo() { string x{"abc"}; return x; }
void bar() {
    const string& y = foo();
}

为什么不同?可以说"temporay 的生命周期不会在函数调用中延长(即使绑定到 const 引用("?或者什么是解释,为什么第一个可以,但第二个不行?

第一个很好,因为返回值(临时值(直接绑定到对 const 的引用,然后临时值的生存期延长到引用的生存期。

请注意,在第两种情况下没有临时的,x是一个局部变量,当退出函数时将被销毁,那么该函数将始终返回一个悬空的引用;该引用用于初始化y但没有任何变化,y也将是一个悬空的引用。