Returning reference to a local variable

前端 未结 7 1248
忘掉有多难
忘掉有多难 2020-12-18 14:04

Why can this code run successfully in Code::block. The IDB just reports

warning: \"reference to local variable ‘tmp’ returned\",

7条回答
  •  一个人的身影
    2020-12-18 14:30

    As you can see the below example code is just slightly modified by calling goodByeString(). Like the other answers already pointed out the variable in getString called tmp is local. the variable gets out of scope as soon as the function returns. since it is stack allocated the memory is still valid when the function returns, but as soon as the stack grows again this portion of memory where tmp resided gets rewritten with something else. Then the reference to a contains garbage.

    However if you decide to output b since it isn't returned by reference the contents is still valid.

    #include 
    #include
    using namespace std;
    
    const string &getString(const string &s)
    {
      string tmp = s;
      return tmp;
    }
    
    string goodByeString(const string &s)
    {
      string tmp = "lala";
      tmp += s;
      return tmp;
    }
    
    int main()
    {
       const string &a = getString("Hello World!\n");
       string b = goodByeString("ciao\n");
       cout << a << endl;
       return 0;
    }
    

提交回复
热议问题