将临时对象绑定到const引用

时间:2019-02-08 07:39:57

标签: c++

#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

怎么了?

1 个答案:

答案 0 :(得分:0)

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
    }