Here goes another n00b question:
Why is it that I cannot/shouldn't return the referece 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);
}
C # in TeluguA C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.
It means you return by reference, which is, at least in this case, probably not desired. It basically means the returned value is an alias to whatever you returned from the function. Unless it's a persistent object it's illegal.
Summary: it's okay to return a reference if the lifetime of the object won't end after the call.
C++ functions can return by value, by reference (but don't return a local variable by reference), or by pointer (again, don't return a local by pointer). When returning by value, the compiler can often do optimizations that make it equally as fast as returning by reference, without the problem of dangling references.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With