2013-02-26 43 views
0

我有一些简单的代码将两个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; 
} 
+0

你的问题是什么?为什么你必须“删除”它或为什么内存泄漏是一个问题? – 2013-02-26 16:41:07

+0

@aleguna问题是我为什么在使用像这样删除时出现错误。我不想要内存泄漏。 – Gandalf458 2013-02-26 16:48:05

+0

@ Gandalf458,你听说过“三大法则”吗? – 2013-02-26 16:51:37

回答

0

因为泄漏的内存不能在程序中的其他内容中重复使用。它将保持使用状态,直到您关闭程序并且系统可以回收它。

大多数情况下,您希望将其清理干净,以便重新使用它,因为内存不是无限的资源。

也许对于少量内存而言,泄漏它并不是一个大问题,但是,如果您一次分配256字节的块,并且其中很多,然后泄漏这些可能很快就会成为问题。

+0

我该如何避免这种内存泄漏?删除的呼叫给了我一个断言错误。 – Gandalf458 2013-02-26 17:03:55

相关问题