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);