Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler warning when returning a reference to a local object

Tags:

c++

reference

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.

like image 870
user13645 Avatar asked Jan 23 '26 00:01

user13645


1 Answers

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.

like image 195
James McNellis Avatar answered Jan 24 '26 21:01

James McNellis