Pwnna
Pwnna

Reputation: 9528

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

Upvotes: 21

Views: 16451

Answers (4)

leftaroundabout
leftaroundabout

Reputation: 120711

"What about this one: ..."

s2 + s1 + s2 is itself a temporary local variable, so it can't be returned by reference either.

What you could do - but please don't, this is a memory leak! - is

const string & wrap2(const string & s1, const string & s2){
  string *pt = new string(s2+s1+s2);
  return *pt;
}

This creates a globally valid string, which can then be passed by reference because it's not destroyed after the function finishes executing. In fact, it's never ever destroyed and will occupy space as long as the program runs: you probably don't want that!

If it wasn't a const reference you could, however, delete it manually.

EDIT: so it turns out that you can even delete the const reference, but again - that's not really nice to do.

Upvotes: 4

Seth Carnegie
Seth Carnegie

Reputation: 75130

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.

Upvotes: 10

LuisZaman
LuisZaman

Reputation: 104

Like the previous posters said, it is because local variables end up on the stack. That physical memory could end up being given to another function frame and changed, all while you're pointer is still hanging on to the same location (which is now changed). I am not sure, but I don't think is is "destroyed", but it certainly isn't protected from being changed by any future stack allocations.

Upvotes: 1

QuantumMechanic
QuantumMechanic

Reputation: 13946

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.

Upvotes: 7

Related Questions