【问题标题】:binding a temporary object to a const reference [duplicate]将临时对象绑定到 const 引用
【发布时间】:2019-07-02 10:18:33
【问题描述】:
#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

怎么了?

【问题讨论】:

  • f() 函数中的 x 是函数的局部变量,并且在函数返回时被“销毁”(分配在调用堆栈上)。因此,如果您尝试返回对该已破坏变量的引用,则会导致错误。
  • 您可能想get a couple of good books 了解变量的生命周期。

标签: c++


【解决方案1】:
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
    }

【讨论】:

  • 这是一个不错的小内存泄漏。
猜你喜欢
  • 2016-11-09
  • 1970-01-01
  • 2012-07-18
  • 2018-08-14
  • 1970-01-01
  • 2013-07-04
  • 2019-12-21
相关资源
最近更新 更多