0

I was just trying a few things out, as I am just starting with C++. I don't get the following error statement:

#include <string>

using namespace std;
string& s6(string a) {return a;}
int main() {

    string a = "helloo";

    s6(a);

    return 0;
}

Then I get the following warning:

Untitled.cpp:4:30: warning: reference to stack memory associated with local variable 'a' returned [-Wreturn-stack-address]
string& s6(string a) {return a;}
                             ^
1 warning generated.

What does this exactly mean?

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
Susan
  • 1

1 Answers1

3

What that message means is that you are returning a reference to a local variable, and that's bad and will lead to undefined behavior.

Local variables, like variables declared inside functions, but also arguments to functions, are local to the function and are destructed when they go out of scope (the function returns). If you return a reference to a local variable, when the function returns you will have a reference to some object that no longer exists.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621