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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With