赋值运算符在不应该返回"empty"实例时返回?

Assignment operator is returning an "empty" instance when it shouldn't?

本文关键字:返回 实例 empty 赋值运算符 不应该      更新时间:2023-10-16

我正在实现一个堆栈只是为了练习。那么,在main中,我有这样的东西:

Stack stack;
stack.push(element1;
stack.push(element2);
Stack copy;
copy = stack;

所以我重载赋值操作符,因为我还想生成新的元素实例(而不仅仅是将每个元素的指针从一个复制到另一个),如下所示

Stack &Stack::operator=(const Stack &toCopy) {
    Stack* stack = new Stack;
    if (toCopy.first == NULL) return *stack;
    for (Node* actual = toCopy.first; actual != NULL; actual = actual->sig) {
        stack->push(actual->elem);
    }
    // In this state, *stack has 2 elements as it should
    return *stack;
}

回到主程序中,copy变量没有得到更改…它仍然是空的,好像约会从未发生过。就好像我只做了Stack copy;,你能解释一下这里发生了什么吗?

您没有修改当前对象(即*this)。

你只是通过new创建一个新对象,然后返回它。注意,对于copy = stack;,它相当于copy.operator=(stack);,注意返回值不被使用,它只是被丢弃(并导致内存泄漏),并且copy没有改变。

你应该这样做:

Stack &Stack::operator=(const Stack &toCopy) {
    // do some work to clear current elements in *this
    // ...
    // add elements from toCopy
    for (Node* actual = toCopy.first; actual != NULL; actual = actual->sig) {
        this->push(actual->elem);
    }
    // operator= is supposed to return *this in general
    return *this;
}

您可能误解了赋值操作符。它在等号左边的对象上下文中起作用。所以你的::operator=(...)应该总是在*this上工作,也应该总是返回*this

您发布的operator=(...)正在操作您在堆上分配的堆栈对象,并且您正在操作而不是*this

您可以有效地将代码中的stack替换为this。例如:

Stack &Stack::operator=(const Stack &toCopy) {
    //Stack* stack = new Stack; // Don't do this.
    if (toCopy.first == NULL) return *this;
    for (Node* actual = toCopy.first; actual != NULL; actual = actual->sig) {
        this->push(actual->elem); // You could also just call push without "this->"
    }
    // In this state, *stack has 2 elements as it should
    return *this;
}