I will start by saying I’ve read this topic: C++ Return reference / stack memory. But there, the question was with an std::vector<int> as object-type. But I though the behavior of std::string was different. Wasn’t this class especially made for using strings without having to worry about memory-leaks and wrong usage of memory?
So, I already know this is wrong:
std::vector<t> &function()
{
vector<t> v;
return v;
}
But is this wrong as well?
std::string &function()
{
string s = "Faz";
s += "Far";
s += "Boo";
return s;
}
Thanks
Extra question (EDIT): So, am I correct when I say returning (by value) an std::string doesn’t copy the char sequence, only a pointer to the char * array and an size_t for the length?
If this statement is correct, is this the valid way to create a deep copy of a string (to avoid manipulating two strings at once)?
string orig = "Baz";
string copy = string(orig);
You are really close to making those functions work:
Simply make them return a copy instead of a reference and you’re set. This is what you want, a copy of the stack-based string.
It gets better too, because the return value optimization (RVO) will only create the string once and return it, just like if you had created it on the heap and returned a reference to it, all behind the scenes!