我正在尝试为我的班级重载 operator + ,如下所示:
MyClass MyClass::operator +(const MyClass& rval) const {
MyClass ret(m_src); // m_src is member of MyClass: char* m_src;
ret.Add(rval); // this->m_src + rval, this method work correctly
return ret; // so, in ret.m_src I have correct value
} // but after this C++ call destructor for ret
析构函数:
delete[] m_src; // because in some methods I allocate dynamic memory
因此,析构函数清除内存和函数返回垃圾。我怎样才能避免这种情况?如果我删除析构函数,函数工作正常,但在这种情况下我有内存泄漏:(
PS:不幸的是,我无法更改重载+的原型。谢谢。