is it possible to return a reference from a function like in this example code:
string &erase_whitespace(string &text)
{
text.erase(**etc.**);
return text;
}
Call:
string text = erase_whitespace(string("this is a test"));
cout << test;
Does this code work? On Visual C++ it does not crash but it looks wrong.
Thanks
From § 12.2.3 of the C++ 2003 standard (draft)
§ 12.2.4:
§ 12.2.5:
§8.5.3.5 is what determines when the reference must be a const type. It is possible for a temporary to be bound to a non-const reference if the temporary is an instance of a class that has a conversion operator that returns an appropriate reference (that’s a mouthful). An example might be easier to understand:
The last line isn’t valid because of § 12.3.2.1, which states “A conversion function is never used to convert [an …] object to the […] same object type (or a reference to
it)”. You might be able to make it work using casting via an ancestor of Bar and a virtual conversion function.
An assignment is an expression (§ 5.17), thus the full-expression (§ 1.9.12) in your code is the assignment. This gives the following sequence (forgetting for the moment that a temporary string probably can’t be bound to a non-const reference):
string& textargument oferase_whitespaceerase_whitespacedoes its thang.erase_whitespacereturns a reference to the temporarystring textSo all is kosher in this case. The problem case, as Mike Seymour points out, would be assigning the result of
erase_whitespaceto a reference. Note that this likely wouldn’t cause an immediate problem, as the area that stored the string probably contains the same data it did before the temporary was destroyed. The next time something is allocated on the stack or heap, however…