0

内存管理:字符数组和 = 运算符

问:在内存管理方面,您使用以下代码会有什么错误?

class String
{
public:
 String(const char right[]);
 String& operator= (const String& right);
 int length() const;
private:
 char* buffer;
 int len;
};

int String::length() const {return len;}

String::String(const char right[])
{
  len = 0;
  while (right[len] != '\0')
    len++;
  buffer = new char[len+1];
  for (int i = 0; i < len; i++)
    buffer[i] = right[i];
  buffer[len] = '\0';
}

String& String::operator= (const String& right)
{
  int n = right.length();
  for (int i = 0; i <= n; i++)
    buffer[i] = right.buffer[i];
  return *this;
}

回答。我不知道...你能帮帮我吗?数组大小似乎还可以......新运算符......是因为没有删除运算符而导致悬空指针吗?还是三法则?

我会很感激你的帮助!请告诉我。谢谢,

4

1 回答 1

0

我只能建议

~String()
{
    if(buffer)
        delete [] buffer;
    len = 0;
}

String(int length)
{
  buffer = new char[length];
  len = length;
}

String String::operator = (String rhs)
{
    if(this != &rhs)
    {
        delete [] buffer;
        buffer = new char[strlen(rhs.m_str) + 1];
        strcpy(buffer, rhs.buffer);
    }

    return *this;
}

如果您没有析构函数,那么每次在类中新建缓冲区时,都会发生内存泄漏,因为您的代码无法摆脱它。

于 2013-04-23T05:45:12.940 回答