创建了我自己的字符串类,它在调用重载赋值运算符时意外中断(即我相信)。它在调用重载赋值运算符后尝试删除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';
}
答案 0 :(得分:2)
operator=()
如果this->mStr
包含nullptr
,delete[]
rhs
的{{1}}可能会因nullptr
分配给operator+=()
,而this->mStr
可能会导致内存泄漏。strcat()
{{1}}在连接之前没有延长。这意味着{{1}}将写入不应存在的内存,导致未定义的行为,并且可能是析构函数中出现问题的原因。答案 1 :(得分:1)
我认为这是一个练习(否则你会使用std::string
)。您的问题似乎是operator+=
仅为您要添加的字符串分配足够的空间,不足够的空间用于原始字符串和您应用到其结尾的新部分。您需要分配更多空间:char * newSize = new char[strlen(this->mStr) + length + 1];
,然后删除旧的字符串指针并将newSize
指针指定给类成员。