我正在编写一个字符串类,在进行赋值运算符重载时,我在删除先前分配的内存的部分观察到崩溃。我试图追踪代码,但无法弄明白。任何指针都会有所帮助
str& str::operator=(const str &Rhs)
{
if (this != &Rhs)
{
cout << " attempt of self allocation - " << endl;
**delete[] this->_element;** // crashes here
this->_capacity = Rhs._capacity;
this->_display = Rhs._display;
this->_size = Rhs._size;
if (Rhs._size > 0)
{
this->_element = new char(this->_size);
if (this->_element == NULL)
{
cout << " mem allocation failed " << endl;
}
}
for (int counter = 0; counter <= this->_size; counter++)
{
this->_element[counter] = Rhs._element[counter];
}
}
return *this;
}
/*copy constructor */
str::str(const str& Rhs)
{
// copy constructor called
this->_capacity = Rhs._capacity;
this->_display = Rhs._display;
this->_size = Rhs._size;
if (Rhs._size > 0)
{
this->_element = new char(_size);
if (this->_element == NULL)
{
cout << " mem allocation failed " << endl;
}
for (int counter = 0; counter <= this->_size; counter++)
{
this->_element[counter] = Rhs._element[counter];
}
}
}
/ *构造函数* /
str::str(const char *Y)
{
cout << "constructor called !!! -- " << endl;
size_t len = this->stringlen(Y);
this->_element = new char(len + 1);
for (int counter = 0; counter < len; counter++)
{
this->_element[counter] = Y[counter];
}
this->_element[len] = '\0';
this->_size = len + 1;
cout << "string in constructor is -- " << this->_element << endl;
}
来自.h文件
class str
{
public:
/*Default Constructor*/
explicit str();
/*Constructor with single char Argument*/
explicit str(char x);
/*Constructor with char array Argument*/
explicit str(const char* Y);
/* Creating new element with copy constructor */
str(const str& Rhs);
/* Overloading of Assignment operator */
str& operator=(const str& Rhs);
friend int string_compare(const str& Lhs, const str& Rhs);
int reverse();
size_t stringlen(const char* Y);
str& operator+(str& Rhs);
bool operator==(const str& Rhs);
bool operator!=(const str& Rhs);
friend ostream& operator<<(ostream &out, str& Lhs);
private:
char* _element;
int _capacity;
bool _display;
int _size; //largest accessed + 1
};
主要例程 -
void test1() {
const char *j = "abc";
cout << "length of j = " << strlen(j) << endl;
str s1('U');
str s2("hello");
cout << s2 << endl;
s2.reverse();
cout << s2 << endl;
str s3(s2);
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
**s2 = s1;** // crashes
cout << s2 << endl;
cout << s1 << endl;
}
答案 0 :(得分:1)
您的代码存在一些问题。
最大的一个是:如果要分配数组,则需要使用new char[_size]
。 new char(_size)
分配一个char,其值设置为_size
。
其次,一旦你解决了这个问题,你就会写出已分配数组的结尾 - 根据标题中的注释判断你需要分配char[_size + 1]
。
第三,在您的复制构造函数中,您永远不会初始化_element
数组,并且在赋值运算符中,您永远不会清除_element
值。当您复制或分配空str
然后尝试分配给它时(或者在销毁时我假设析构函数也调用delete
),这最终会导致崩溃。