创建了自己的字符串类——重载赋值操作符和析构函数的错误
Created my own string class -- errors with overloaded assignment operator and destructor
创建了我自己的字符串类,当它调用重载赋值操作符时意外中断(即我相信)。当调用重载赋值操作符后试图删除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;
}
<<p> 字符串构造函数/strong> 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]= ' ';
}
- 如果
rhs
包含nullptr
,this->mStr
被分配给nullptr
而没有delete[]
,operator=()
可能存在内存泄漏 - 在
operator+=()
中,this->mStr
在连接之前没有被扩展。这意味着strcat()
将写入内存,它不应该这样做,导致未定义的行为,可能是析构函数中看到的问题的原因。
我假设这是一个练习(否则您将使用std::string
)。您的问题似乎是operator+=
仅为您添加的字符串分配足够的空间,而不是足够的空间用于原始字符串和添加到其末尾的新块。您需要分配更多的空间:char * newSize = new char[strlen(this->mStr) + length + 1];
,然后删除旧的字符串指针并将newSize
指针分配给类成员。
相关文章:
- 不命名构造函数和析构函数上的类型错误
- 导致 Seg 错误的 SingleLinkedList 的析构函数
- LINUX 操作系统上的错误:令牌之前预期的构造函数、析构函数或类型转换'('?
- 矢量擦除调用的错误析构函数
- 在析构函数中调用"delete"运算符时"compiler is out of heap space"编译器错误
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 导致堆缓冲区错误的动态分配数组的析构函数
- Qt C++析构函数错误
- C++ 链接列表队列实现和析构函数错误:"Aborted (Core Dumped)"
- 使用此指针时出现C++析构函数错误的原因
- 是否有某种方法可以检测是否使用非虚拟基析构函数错误地删除了类
- 类析构函数错误
- 析构函数错误
- C++动态数组析构函数错误
- c++中对析构函数错误的未定义引用
- 字符数组的析构函数错误
- C++复制构造函数、析构函数错误等
- 无法退出,因为析构函数错误导致main()在退出时停止执行
- 映射析构函数错误
- c++析构函数错误