2

我收到此功能的错误。说“警告:对返回的局部变量‘final’的引用”有什么想法吗?以及如何解决?

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);


}
4

2 回答 2

7
std::vector<int>& find1(std::string& search_word)
{

Here, you're returning a reference. A reference is an alias to an object. The object that is returned by this function will bind to the reference and be returned to the caller.

    std::vector<int> final;

This is a local variable with automatic storage-duration. At the end of this function (meaning the closing brace) the vector will be deallocated and erased from the stack.

     ...
     return final;
}

For this reason, returning a local variable from a function by reference is Undefined Behavior. Your program is now in an ill-formed state.

int main()
{
    ...
    std::vector<int>& p = find1(search);
}

p is also a reference, meaning it is an alias for the object that is returned. This is also wrong because the object that you think was returned was actually deallocated when the function returned.

To fix, return by value:

std::vector<int> find1(std::string& search_word)

Also, use an object, not a reference:

std::vector<int> p = find1(search);
于 2013-10-15T00:00:21.477 回答
3

您正在返回对局部变量的引用。当find1函数返回时,对象final被销毁。

更新

vector<int> & find1(string &search_word)
//          ^^

vector<int> find1(string &search_word)
于 2013-10-14T23:55:11.713 回答