我的任务是使用指针数组创建类 stack
。但是,当我将 stack
类型的变量分配给自身时,堆栈(或数组)的元素变成垃圾。所以这是代码(字段是 array
、stack_size
和 stack_capacity
):
stack& operator= (const stack& old)
{
if (stack_size != old.stack_size) {//array and old.array could be the same
delete[] array;
}
stack_size = old.stack_size;
stack_capacity = old.stack_capacity;
array = new int[stack_capacity];
for (size_t i = 0; i < stack_size; ++i) {
array[i] = old.array[i];
}
return *this;
}
但是,当我跑步时
std::cout << "Peek: " << c.peek() << " Size: " << c.size() << std::endl;
std::cout << c << "\n\n";
输出(分配前)是:
Peek: 300 Size: 6
{ -88, 99, -100, 0, 200, 300 }
并在分配后(stk = stk)是:
Peek: -842150451 Size: 6
{ -842150451, -842150451, -842150451, -842150451, -842150451, -842150451 }
可能是什么问题?有什么我想念的吗?谢谢
答案 0 :(得分:1)
由于 *this
和 old
是同一个对象,因此 this->array
与 old.array
相同。
这意味着您正在复制
array = new int[stack_capacity];
融入自身。
传统的快速解决方法是先检查自分配,
if (this == &old)
return *this;
更现代的解决方案是“复制和交换”习语,您可以在线阅读。