How to have the return string alias can be 'seen' with the defined name in caller scope, without being as global nor passing it off ?
illustration is sort of:
#include <iostream>
#include <string>
std::string& func(std::string&);
int main()
{
std::string str("Hello");
std::string result { func(str) };
std::cout << result << '\n';
}
std::string& func(std::string& str)
{
std::string ret_str { str + " World" };
// this returns a temp string, this leads to undefined behavior
// very bad, do not do it!
return ret_str;
}
@Furry Guy
You may add a comment (at least line 20 of your first example) to make clear that it is an erroneous return. This kind of bugs are hard to detect.
Additionally, are you allowed to move local variables? I'm guessing not because the memory "stolen" will be on the previous stack and thus invalid once the called function returns?
You just need to remove the return by reference so you get a copy back, don't you?
I don't understand why you want to return a string at all here. You're passing str by reference, so whatever the calling code passes in will already be modified.
What purpose is there in also returning the modified string?
I am responsible for all your vexations, so say sorry.. it's just a notion on "modern" programming language, is there one such feature ?
When I wrote first, on mind was friend or some new C++17 breakthrough or whatever useful brilliant idea by the committee...
Thanks all.