xok*_*xoo 3 c++ string operators operator-keyword
所以有问题的代码是这样的:
const String String::operator+ (const String& rhs)
{
String tmp;
tmp.Set(this->mString);
tmp.Append(rhs.mString);
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
这当然将String放在堆栈上,它被删除并返回垃圾.将它放在堆上会泄漏内存.那我该怎么做呢?
hjh*_*ill 11
如果你有一个工作的复制构造函数,你的解决方案不会返回垃圾 - tmp在块结束时销毁String 对象之前将其复制到结果对象中.
您可以通过替换来做得更好
String tmp;
tmp.Set(this->mString);
Run Code Online (Sandbox Code Playgroud)
同
String tmp(*this);
Run Code Online (Sandbox Code Playgroud)
(你需要一个正确工作的复制构造函数,但是你的return语句无论如何都需要它)
| 归档时间: |
|
| 查看次数: |
246 次 |
| 最近记录: |