引用用于类对象,为什么运行会崩溃

#include <iostream>
#include <string>
using namespace std;
const string & version3(string & s1, const string & s2); // bad design
int main()
{
 string input;
 string copy;

 string result;
 cout << "Enter a string: ";
 getline(cin, input);
 copy = input;
 cout << "Your string as entered: " << input << endl;
result = version3(input, "@@@");
 cout << "Your string enhanced: " << result << endl;
 cout << "Your original string: " << input << endl;
 return 0;
const string & version3(string & s1, const string & s2) // bad design
{
 string temp;
 temp = s2 + s1 + s2;
 // unsafe to return reference to local variable
 return temp;
}
答案时程序试图引用已释放的内存  但是没看到啊,难以理解
xungeer29
浏览 1342回答 1
1回答

onemoo

main 函数缺了尾大括号,不过应该是贴代码时落下了吧。在 version3 中,你返回的是函数中的变量 temp。这个 temp 的作用域仅在函数之中,在函数运行结束后 temp 会被销毁,这样返回的这个引用就引用无效对象了。在函数返回引用时一定要注意不要返回函数的 local 变量。
打开App,查看更多内容
随时随地看视频慕课网APP