references/pointers

Hey,

For an assignment I have to use this method :

std::string& RowIterator::next(int& columnNr){
current=current->next;
columnNr=current->columnNr;
std::string s = current->word;
return s;
};

However, each time I debug, I get this warning :
returning adress of local variable or temporary

Which results in the output of my program only consisting of empty strings (s is always empty).
How can I solve this when my method has to return a string&?
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
Since I have to respect the signature of the method, I have to return by reference so I chose the second method and now it's working. Thanks!
Topic archived. No new replies allowed.