使用运算符=将链接列表堆栈的副本创建到另一个堆栈中

问题描述 投票:0回答:1

我正在学习cpp,我已经能够成功创建堆栈,但是我想知道一个人如何在没有任何内存泄漏的情况下将其复制到另一个上。我不断出现分段错误(核心已转储)..这是第一次使用operator =,所以我不太确定如何处理它]

template <class Type>
class stack{
private:
    node<Type> *top;
public:
    stack(){
        top = NULL;
    }

    stack(const stack& other) {
    top = other.top;
    *this = other;
}

    stack& operator=(const stack& rhs)
    {
        node<Type> *start = nullptr;
        node<Type> *last = nullptr;
        node<Type> *current = top;

        while (current != NULL){
            node<Type> *newNode = new node<Type>(current->data);
            if (start = nullptr){
                start = newNode;
            }
            else {
                newLast->next = newNode;
            }
            last = newNode;
            newNode->next = nullptr;
            current = current->next;
            }
          /* REST OF STACK FUNCITONS */
    }

我试图指出几件事以查看会发生什么,并且我具有我所需要的值,只是不确定如何转移

stack& operator=(const stack& rhs)
{
    display(); //1.36->2.61->3.45->4.94
    cout<<"\n";
    cout<<top->data<<endl; //4.94
    cout<<rhs.top->data<<endl; //4.94
    return *this;
}

这就是我要运行的内容,它给了我核心转储错误

int main(){
    stack<double> mystack;
    mystack.push(1.36);
    mystack.push(2.61);
    mystack.push(3.45);
    mystack.push(4.94);

    stack<double>copy_mystack(mystack);

    return 0;
}
c++ pointers linked-list stl stack
1个回答
0
投票

[我建议您首先实现正确的复制构造器,该复制器将进行深复制,并使用swap成员函数,然后仅将stack{rhs}.swap(*this);用于operator=

template<class T>
class stack {
private:
    node<T>* top;

public:
    stack() : top(nullptr) { }

    stack(const stack& other) {
        auto tail = &top;
        for (auto ptr = other.top; ptr; ptr = ptr->next) {
            *tail = new node<T>{ptr->data};
            tail = &(*tail)->next;
        }
        *tail = nullptr;
    }

    ~stack() {
        while (top) {
            auto next = top->next;
            delete top;
            top = next;
        }
    }

    stack& operator=(const stack& other) {
        stack{other}.swap(*this);
        return *this;
    }

    void swap(stack& other) {
        std::swap(top, other.top);
    }

    // ...
};

[operator=首先复制other,然后与*this交换,然后销毁原始列表。

© www.soinside.com 2019 - 2024. All rights reserved.