简体   繁体   中英

C++ function return reference

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

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.

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.

"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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM