0
#include <iostream>
#include <string>

using namespace std;


string& funRef (string& s) {
string t = s;


return t;
}

int main() {
string s1 = "I'm a string!";
string& s2 = funRef(s1);
s2 = "YOUR STRING IS MINE";

cout << s1 << endl;
cout << s2 << endl;
}

why does it print out:

I'm a string!

\367\277_\377\367\277_\377M

I thought s2 was assigned with "YOUR STRING IS MINE".

what happen to the s2?

Pelican
  • 43
  • 7
  • It references a destroyed object, `string t = s;` `t` is destroyed when `funref` is no longer in scope. – George Feb 06 '17 at 23:43

1 Answers1

0

Most of your code is irrelevant.

This comes down to simple undefined behaviour, because here you are returning a reference to a local variable:

string& funRef(string& s)
{
   string t = s;
   return t;
}

The string t dies as soon as the call to funRef ends, but you're trying to use a reference to t later.

You can't do that.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055