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);
}
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.