我有一些简单的代码将两个char []合并到一个新数组中。问题是,当我创建新的数组时,我想删除在构造函数中分配的原始char数组。如果我不在这个内存上调用delete,那么一旦我重新分配了m_str,我会得到一个内存泄漏。如何使用它删除成员函数中的成员数组,用于重新赋值
-Edit 为什么我在调用delete时出错?
String() { m_str = new char[1]; *m_str = 0; }
String& String::operator+= (const String& other)
{
unsigned int tmpInt1, tmpInt2;
tmpInt1 = myStrlen(this->m_str);
tmpInt2 = myStrlen(other.m_str);
// Allocate the new char array, make an extra space for the '\0'
char* newChar = new char[tmpInt1 + tmpInt2 + 1];
myStrcat(newChar, this->m_str, tmpInt1, 0);
myStrcat(newChar, other.m_str, tmpInt2, tmpInt1);
this->m_str[myStrlen(m_str)] = '\0';
delete[] this->m_str;
this->m_str = newChar;
return *this;
}
你的问题是什么?为什么你必须“删除”它或为什么内存泄漏是一个问题? – 2013-02-26 16:41:07
@aleguna问题是我为什么在使用像这样删除时出现错误。我不想要内存泄漏。 – Gandalf458 2013-02-26 16:48:05
@ Gandalf458,你听说过“三大法则”吗? – 2013-02-26 16:51:37