C++编译时出现 reference to local variable

具体见:https://stackoverflow.com/questions/19371137/c-reference-to-local-variable-returned

  • 会引发问题的实现如下:

vector<int> & find1(string &search_word)
{
    vector<int> final;
final.push_back(2);
final.push_back(5);


return (final); //This is giving me the error when I try to return the vector.

}

int main ()

{
string search;

cin >> search;

vector <int> &p = find1(search);


}

  • 修改find1方法返回对象而不是引用
//错误的
//在find1方法结束时,方法内部的局部变量就会被清楚
std::vector<int>& find1(std::string& search_word)
std::vector<int>& p = find1(search);

//正确的
//使用对象,而不是引用
vector<int> find1(string &search_word); //返回类型从引用变成对象
std::vector<int> p = find1(search);

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页