1

Consider this:

std::vector<std::string> f() //some irrelevant function
{
    std::vector<std::string> tempCol;
...//some more irrelevant stuff
    return tempCol;
}

const std::vector<std::string>& refToLocal = f();

I know that this compiles and runs perfectly. I even know even that is is used variously in the production code. So the question is, does the local object must be deleted after the function scope?? how the reference 'attaches' to must have deleted local object???

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • 2
    It is not a reference to the local value, it is a reference to the *copy* returned by the function. It returns a value, not a reference. – Bo Persson Nov 09 '17 at 12:01
  • yes but the copy also must be deleted – Eduard Rostomyan Nov 09 '17 at 12:02
  • It's a reference to a temporary. –  Nov 09 '17 at 12:02
  • well whatever you call it. how can i get the reference of the temporart? – Eduard Rostomyan Nov 09 '17 at 12:03
  • 1
    related: https://stackoverflow.com/questions/2784262/does-a-const-reference-prolong-the-life-of-a-temporary – W.F. Nov 09 '17 at 12:05
  • You can assign a temporary to a const reference and the life cycle of the temporary will be aligned with that of the reference. – jszpilewski Nov 09 '17 at 12:06
  • 1
    Btw, nowadays with return value optimization (RVO) assigning a non reference function call result to a reference is just an unneeded annoyance. You can assign the result to a value variable (remove &) without any performance penalty. – jszpilewski Nov 09 '17 at 12:22

1 Answers1

3

tempCol (the local variable) is destroyed when the function is finished executing. The return value of the function is a copy of tempCol.

Usually the lifetime of a return value ends as the final step of evaluating the full expression in which it occurs (in this case ... = f();), but since you are binding it to a reference (refToLocal), its lifetime is extended to the lifetime of the reference to which it is bound.

When the variable refToLocal goes out of scope, both it and the function return value are destroyed and memory is reclaimed.

Check out https://stackoverflow.com/a/17903361/2428220 for a more detailed explanation of the lifetime of function return values in C and C++.

sigbjornlo
  • 1,033
  • 8
  • 20