将临时对象绑定到常量引用

binding a temporary object to a const reference

本文关键字:常量 引用 绑定 临时对象      更新时间:2023-10-16
#include <iostream>
using namespace std;
int f() 
{
    int x=1;
    return x;
}
int main()
{
    const int& s = f();
    cout << s << endl;
}

#include <iostream>
using namespace std;
int x=1;
int &f() 
{
    return x;
}
int main()
{
    const int& s = f();
    cout << s << endl;
}

这两个程序都是正确的。但是当我使用

int &f() 
{
    int x=1;
    return x;
}

而不是

int f() 
{
    int x=1;
    return x;
}

我收到一个错误:

main.cpp:在函数'int& f(('中:

main.cpp:6:13: 警告:返回对局部变量 'x' 的引用 [-Wreturn-local-addr]

     int x=1;
         ^

bash:第 7 行:14826 分段错误(核心转储(./a.out

怎么了?

int &f() 
{
    int x=1;
    return x;
   // x reside on the function calling stack and it is temporary
   // when you return the reference to x, after the function has returned, 
   // x is not there anymore(local variable)
}

如果确实要返回对函数内声明的变量的引用,请考虑将其分配给堆,或将其声明为静态变量

    int &f() 
    {
        int* x= new int;
        *x = 1;
        return *x;
    }
    int main(){
        int& a = f();
        cout << a; // 1
        delete &a;
        // and MAKE SURE you delete it when you don't need it
    }