Reputation: 2255
I'm getting an error with this function. Saying " warning: reference to local variable 'final' returned" Any ideas what is wrong with it? And how to fix it?
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);
}
Upvotes: 3
Views: 10619
Reputation: 96845
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);
Upvotes: 8
Reputation: 45450
You are returning a reference to a local variable. When find1
function returns, object final
is destroy.
update
vector<int> & find1(string &search_word)
// ^^
to
vector<int> find1(string &search_word)
Upvotes: 3