CString& CString::operator +=(const CString & str)
{
strcat(this->m_pCString, str.m_pCString);
return *this;
}
上面是一个重载CString(operator+=)的重载函数,看似没有问题,一路跟踪,发现this->m_pCString的内存内容确实和str.m_pCString拼接一起了,但是再程序退出时候,在析构函数那儿出了问题。
遂换了一种老实的写法,重新申请内存,之后再拷贝和拼接:
CString& CString::operator +=(const CString & str)
{
int lenth = str.GetLenth()+this->GetLenth();
char*p = new char[lenth + 1];
strcpy(p, this->m_pCString);
strcat(p, str.m_pCString);
delete[]this->m_pCString;
this->m_pCString = p;
return *this;
}
再运行之,析构都没有问题。
总结:内存无申请不释放,要释放的地方若是没有申请匹配的大小,则会出错,明智的做法是:申请多大,释放多大!