This happens when returning a zero-hour reference to a function.
3.cc: In function ‘const string& add_(const string&, const string&, const string&)’:
3.cc:6:12: warning: reference to local variable ‘s’ returned [-Wreturn-local-addr]
string s = s1;
例如:
#include <iostream>
#include <string>
using namespace std;
const string & add_(const string &s1,const string & pre,const string & behind)
{
string s = s1;
s.insert(0,pre);
s.append(behind);
return s;
}
int main()
{
string name = "robert";
string pre = "Mr.";
string hi = "Jr.";
string new_name = add_(name,pre,hi);
cout << new_name << endl;
return 0;
}
The result of the compilation is:
r@r-Sys:~/c++/ex$ g++ 3.cc -o 123
3.cc: In function ‘const string& add_(const string&, const string&, const string&)’:
3.cc:6:12: warning: reference to local variable ‘s’ returned [-Wreturn-local-addr]
string s = s1;
^
Error analysis:
The c++ function will destroy the zero-hour amount at the end, and it is of course wrong for the function to return the zero-hour amount. Because it has been destroyed, its reference has no meaning.