为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C C++
xungeer29 2017-10-22 13:37:55
#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; } 答案时程序试图引用已释放的内存  但是没看到啊,难以理解
查看完整描述

1 回答

已采纳
?
onemoo

TA贡献883条经验 获得超454个赞

main 函数缺了尾大括号,不过应该是贴代码时落下了吧。


在 version3 中,你返回的是函数中的变量 temp。这个 temp 的作用域仅在函数之中,在函数运行结束后 temp 会被销毁,这样返回的这个引用就引用无效对象了。


在函数返回引用时一定要注意不要返回函数的 local 变量。

查看完整回答
1 反对 回复 2017-10-22
  • 1 回答
  • 0 关注
  • 1337 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信