Question

C++ function return reference

Why is it that I cannot/shouldn't return the reference to a local variable to a function? Is it because the temporary variable is automatically destroyed after the function finishes executing?

const string & wrap(string & s1, const string & s2){
    string temp;
    temp = s2 + s1 + s2;
    return temp;
}

What about this one:

const string & wrap2(const string & s1, const string & s2){
    return (s2 + s1 + s2);  
}
 21  16438  21
1 Jan 1970

Solution

 10

Variables declared locally inside functions are allocated on the stack. When a function returns to the caller, the space on the stack where the variable used to reside is reclaimed and no longer usable and the variables that were there no longer exist (well they do but you can't use them, and they can be overwritten at any time). So yeah, basically what you said.

2011-05-12

Solution

 7

That's exactly it. The local variable goes poof and is destroyed when it goes out of scope. If you return a reference or pointer to it, that reference or pointer will be pointing at garbage since the object won't exist anymore.

2011-05-12