gpt4 book ai didi

c++ - 赋值运算符重载——删除堆内存导致崩溃

转载 作者:行者123 更新时间:2023-11-28 06:01:55 25 4
gpt4 key购买 nike

我正在写一个字符串类,在进行赋值运算符重载时,我观察到在我们删除以前分配的内存的部分发生崩溃。我试图通过代码进行追踪,但无法弄清楚。任何指针都会有所帮助

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;

最佳答案

您的代码有几个问题。

  • 最大的一个是:如果你想分配一个数组你需要使用new char[_size]new char(_size) 分配一个 char,其值设置为 _size

  • 其次,一旦您解决了该问题,您就会写入已分配数组的末尾 - 根据 header 中的注释判断,您需要分配 char[_size + 1]

  • 第三,在您的复制构造函数中,您永远不会初始化 _element 数组,并且在您的赋值运算符中,您永远不会清除 _element 值。当您复制或分配一个空的 str 然后尝试分配给它时(或者在销毁时,我假设析构函数也调用 delete ),这最终会导致崩溃.

关于c++ - 赋值运算符重载——删除堆内存导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33110401/

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