c++ return reference / stack memory [duplicate]

旧街凉风 提交于 2019-12-03 18:01:54

问题


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.


回答1:


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




回答2:


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



回答3:


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




回答4:


You can't return a reference to a local variable for the same reason you can't return a pointer to a local variable, because on return from the function those local variables are deallocated and therefore the reference or pointer becomes invalid.



来源:https://stackoverflow.com/questions/3252292/c-return-reference-stack-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!