C++。 class 中指针数组的赋值运算符
C++. Assignment operator of a pointer array in class
我的任务是使用指针数组创建 class 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 }
可能是什么问题?我有什么想念的吗?谢谢
因为*this
和old
是同一个对象,所以this->array
和old.array
是一样的。
这意味着您正在复制
中的未初始化数据
array = new int[stack_capacity];
进入自身。
传统的快速修复方法是先检查自分配,
if (this == &old)
return *this;
一个更现代的解决方案是“复制和交换”惯用语,您可以在线阅读。
我的任务是使用指针数组创建 class 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 }
可能是什么问题?我有什么想念的吗?谢谢
因为*this
和old
是同一个对象,所以this->array
和old.array
是一样的。
这意味着您正在复制
array = new int[stack_capacity];
进入自身。
传统的快速修复方法是先检查自分配,
if (this == &old)
return *this;
一个更现代的解决方案是“复制和交换”惯用语,您可以在线阅读。