创建了我自己的string类,当它调用重载赋值运算符(我相信)时,它意外地中断。在调用重载赋值运算符之后,当它试图删除mStr时,它就会中断。
被删除的mStr是“\n白金:5\n黄金:5\n银:6\n铜: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';
}
发布于 2013-04-12 19:31:28
operator=()
中包含nullptr
,则this->mStr
中可能会将内存泄漏分配给没有delete[]
的nullptr
。operator+=()
中,this->mStr
没有在级联之前进行扩展。这意味着strcat()
将写入内存,它不应该是,导致未定义的行为,并可能是在析构函数中看到的问题的原因。发布于 2013-04-12 19:59:35
我假设这是一个练习(否则您将使用std::string
)。您的问题似乎是,operator+=
只为您要添加的字符串分配足够的空间,而不为原始字符串和到其末尾的新段分配足够的空间。您需要分配更多的空间:char * newSize = new char[strlen(this->mStr) + length + 1];
,然后删除旧的字符串指针,并将newSize
指针分配给类成员。
https://stackoverflow.com/questions/15979394
复制相似问题