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.
In your example, you are returning a reference to the local variable
str. As soon asGetString()returns,stris 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
strby value. The most common use for returning a reference is for member functions that return a reference to a member variable.