Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function return reference

Tags:

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);  
}
like image 783
Pwnna Avatar asked May 12 '11 23:05

Pwnna


People also ask

Can you return by reference in C?

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.

What does return a reference mean?

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.

Should I return a reference?

Summary: it's okay to return a reference if the lifetime of the object won't end after the call.

Does C++ return by value or reference?

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.


2 Answers

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.

like image 40
QuantumMechanic Avatar answered Nov 09 '22 09:11

QuantumMechanic


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.

like image 71
Seth Carnegie Avatar answered Nov 09 '22 09:11

Seth Carnegie