Reputation: 23
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.
Upvotes: 2
Views: 243
Reputation: 1799
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).
Upvotes: 0
Reputation: 355049
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.
Upvotes: 14