C++。类中指针数组的赋值运算符

时间:2021-02-09 15:43:04

标签: c++ class pointers stack

我的任务是使用指针数组创建类 stack。但是,当我将 stack 类型的变量分配给自身时,堆栈(或数组)的元素变成垃圾。所以这是代码(字段是 arraystack_sizestack_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 }

可能是什么问题?有什么我想念的吗?谢谢

1 个答案:

答案 0 :(得分:1)

由于 *thisold 是同一个对象,因此 this->arrayold.array 相同。
这意味着您正在复制

中未初始化的数据
array = new int[stack_capacity];

融入自身。

传统的快速解决方法是先检查自分配,

if (this == &old)
    return *this;

更现代的解决方案是“复制和交换”习语,您可以在线阅读。

相关问题