tags:

views:

93

answers:

2

How should i return a reference to object without getting a warning for example:

std::string& GetString()
{
    std::string str = "Abcdefghijklmnopqrstuvwxyz";
    return str;
}

int main()
{
    std::string str = GetString();
}

This results a warning on compliation.

+12  A: 

In your example, you are returning a reference to the local variable str. As soon as GetString() returns, str is destroyed and the reference is invalid (it refers to an object that has been destroyed).

If you return a reference to an object, it must be an object that will still be valid after the function returns (e.g., it can't be a local variable).

In this particular case, you have to return str by value. The most common use for returning a reference is for member functions that return a reference to a member variable.

James McNellis
A: 

Technically you could create it to the heap and return a reference (edit: memory leaking example, don't try this at home (thanks James)):

string& GetString() {
    string * strPtr;
    strPtr = new string("qweqweqwe");
    string &str2 = (*strPtr);
    return str2;
}

int main() {
    string str = GetString();
    return 0;
}

But technicalities aside, passing by value is the better option here (as said above).

tsiki
Your example leaks the string allocated by `new`.
James McNellis
I just want to avoid copying the object again.
user13645
@user: There's nothing wrong with copying things. It's done all the time, and needs to be done all the time. Stop worrying about performance and start worrying about good coding practice. Consider even if you could somehow return a reference, like in your question. What happens with `std::string str = GetString();`? `str` is a *copy* of the value returned by `GetString`, regardless of whether it's a reference or not.
GMan
But i could pass str as reference to GetString(str).
user13645
@user: if you really want to avoid copying, you can create the object to heap and return a poiner to it. But still, the normal approach (copy by value) is usually just fine.
tsiki
@user: You could, but your code becomes ugly in the process. Also, C++ isn't a dumb language: the standard permits something called Return-Value Optimization, or RVO. (And Named RVO, NRVO.) Look those up, and you'll see how a modern compiler will essentially do that to your code *anyway*. Might as well stick to the easier to code and clearer to use code. Once your applications actually runs slow, your *profile* it and measure (not guess!) what parts are slow, and what can speed it up. Like I said, good code first, performance *last*.
GMan