When you return a reference, the variable you're referring to must exist past the end of the function.
In your code, you're returning 's', which is a variable local to this function. Consider this:
1 2 3
|
string& foo = iter.next(bar); // calling your function
foo = "explode"; // here, we are really changing 's'
|
'foo' is a reference referring to 's'. IE: when you change 'foo', you are really changing 's'. The problem is,
s no longer exists. It goes out of scope at the end of the next() function. 'foo' is a bad reference, so what ends up happening is you're corrupting memory.
The solution here is either:
- return by value, rather than by reference. Therefore you return a copy of the string, rather than a reference to it.
or
- return something that has a lifetime longer than the function. ie:
return current->word;
instead of s