So the code in question is this:
const String String::operator+ (const String& rhs)
{
String tmp;
tmp.Set(this->mString);
tmp.Append(rhs.mString);
return tmp;
}
This of course places the String on the stack and it gets removed and returns garbage.
And placing it on the heap would leak memory. So how should I do this?
Your solution doesn’t return garbage if you have a working copy constructor – the String object
tmpis copied into the result object before it is destroyed at the end of the block.You could do this better by replacing
with
(you need a correctly working copy constructor for this, but you need it anyways for your
returnstatement)