Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ return reference / stack memory [duplicate]

A basic question that I'm not sure of the answer. Is the follow function valid?

std::vector<int> & test_function() {
   std::vector<int> x;

   // do whatever

   return x;
}

If so, why? Shouldn't the program delete x from the stack after the function returns? Thanks.

like image 957
user1391 Avatar asked Jul 15 '10 03:07

user1391


3 Answers

The behavior is undefined. You shouldn't return references to local variables.

like image 194
Justin Summerlin Avatar answered Sep 27 '22 22:09

Justin Summerlin


The function is well-formed (syntactically correct), but as soon as the function returns, the returned reference is invalid and cannot be used.

To clarify: the code in question does not invoke any undefined behavior. You can safely call this function so long as you do not use the return value, e.g., this is valid:

test_function(); // ok

However, if you try to use the return value (i.e., initialize another reference with it or copy the referent into another object) then you will invoke undefined behavior because the lifetime of the referent (the object x) will have ended (x will be destroyed when the function returns because it is an automatic variable):

std::vector<int>& vec = test_function(); // undefined
std::vector<int> vec = test_function();  // undefined
like image 40
James McNellis Avatar answered Sep 27 '22 23:09

James McNellis


Yes it's valid, but if you attempt to use the returned value, you'll get undefined behavior.

like image 22
Jerry Coffin Avatar answered Sep 27 '22 23:09

Jerry Coffin