gpt4 book ai didi

c++ - 创建了我自己的字符串类——重载赋值运算符和析构函数的错误

转载 作者:行者123 更新时间:2023-11-30 02:55:59 25 4
gpt4 key购买 nike

创建了我自己的字符串类,但它在调用重载赋值运算符时意外中断(我相信)。它恰好在调用重载赋值运算符后尝试删除 mStr 时中断。

被删除的mStr是"\nPlatinum: 5\nGold: 5\nSilver: 6\nCopper: 5 "

我哪里做错了,我怎样才能确保我的程序不会在没有内存泄漏的情况下中断?

代码在这里中断

String::~String()
{
delete [] mStr;
mStr = nullptr;
}

代码在此处中断

    String tempBuffer;

//Store entire worth of potions
tempBuffer = "Platinum: ";
tempBuffer += currencyBuffer[0];
tempBuffer += "\nGold: ";
tempBuffer += currencyBuffer[1];
tempBuffer += "\nSilver: ";
tempBuffer += currencyBuffer[2];
tempBuffer += "\nCopper: ";
tempBuffer += currencyBuffer[3];

mCost = tempBuffer;

重载赋值运算符

String &String::operator=(const String & rhs)
{
//Check for self-assignment
if(this != &rhs)
{
//Check if string is null
if(rhs.mStr != nullptr)
{
//Delete any previously allocated memory
delete [] this->mStr;

//Deep copy
this->mStr = new char[strlen(rhs.mStr) + 1];
strcpy(this->mStr, rhs.mStr);
}
else
this->mStr = nullptr;
}

//Return object
return *this;
}

重载添加和赋值运算符

String &String::operator+=( String rhs)
{
//Check for self-assignment
if(this != &rhs)
{
//Convert to cString
char * buffer = rhs.c_str();

//Find length of rhs
int length = strlen(buffer);

//Allocate memory
char * newSize = new char[length + 1];

//Copy into string
strcpy(newSize, buffer);

//Concatenate
strcat(this->mStr, newSize);

//Deallocate memory
delete [] newSize;

}

//Return object
return *this;
}

复制构造函数

String::String(const String & copy)
:mStr()
{
*this = copy;
}

字符串构造函数

String::String(char * str)
{
//Allocate memory for data member
mStr = new char[strlen(str) + 1];

//Copy str into data member
strcpy(mStr, str);
}

字符的字符串构造函数

String::String(char ch)
{
//Assign data member and allocate space
mStr = new char[2];

//Assign first character to the character
mStr[0] = ch;

//Assign second character to null
mStr[1]= '\0';
}

最佳答案

  • operator=() 中可能存在内存泄漏,因为 this->mStr 被分配给 nullptr 而没有 delete[] 如果 rhs 包含一个 nullptr
  • operator+=()this->mStr 在连接之前没有被扩展。这意味着 strcat() 将写入不应该写入的内存,从而导致未定义的行为,并且可能是析构函数中出现问题的原因。

关于c++ - 创建了我自己的字符串类——重载赋值运算符和析构函数的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15979394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com