这是c++链表的深度复制和正确实现的=操作符吗?

Is this a deep copy and properly implemented = operator for a C++ Linked List?

本文关键字:实现 操作符 链表 c++ 深度 复制 这是      更新时间:2023-10-16

我遇到了一些bug,现在我正试图使用我所做的双重链表类。=操作符的实现如下所示:

template <typename T>
Dlist<T>& Dlist<T>::operator=(const Dlist &l)
{
    copyAll(l);
    return *this;
}
template <typename T>
void Dlist<T>::copyAll(const Dlist &l)
{
    node *copyList = new node;
    copyList = l.first;
    while(copyList){
        insertFront(copyList.first->o);
        copyList = copyList->next;
    }
    delete copyList;
}

注意,0是指向List中某个节点数据的指针。

我的意图是copyAll是一个真正的深拷贝。事实并非如此吗?我的类方法定义有问题吗?我是新的链接列表,所以帮助是非常感激!

编辑:具体来说,我遇到的问题是,当我制作一个列表并填充它时,然后制作一个新列表并将其设置为第一个列表,每当我对第二个列表做一些事情时,它也会改变第一个列表。

EDIT2:这是类本身。我不允许添加任何其他成员函数:

template <typename T>
class Dlist {
 public:
    // Operational methods
    bool isEmpty();
    // EFFECTS: returns true if list is empty, false otherwise
    void insertFront(T *o);
    // MODIFIES this
    // EFFECTS inserts o at the front of the list
    void insertBack(T *o);
    // MODIFIES this
    // EFFECTS inserts o at the back of the list
    T *removeFront();
    // MODIFIES this
    // EFFECTS removes and returns first object from non-empty list
    //         throws an instance of emptyList if empty
    T *removeBack();
    // MODIFIES this
    // EFFECTS removes and returns last object from non-empty list
    //         throws an instance of emptyList if empty
    // Maintenance methods
    Dlist();                                   // ctor
    Dlist(const Dlist &l);                     // copy ctor
    Dlist &operator=(const Dlist &l);          // assignment
    ~Dlist();                                  // dtor
 private:
    // A private type
    struct node {
    node   *next;
    node   *prev;
    T      *o;
    };
    node   *first; // The pointer to the 1st node (NULL if none)
    node   *last;  // The pointer to the 2nd node (NULL if none)

    void makeEmpty();
    // EFFECT: called by constructors/operator= to establish empty
    // list invariant
    void removeAll();
    // EFFECT: called by destructor/operator= to remove and destroy
    // all list elements
    void copyAll(const Dlist &l);
    // EFFECT: called by copy constructor/operator= to copy elements
    // from a source instance l to this instance
 };

基本上浅拷贝深拷贝的区别在于你是复制指针本身还是复制指针指向的所有数据。不要忘记调用基类并复制其所有成员,以避免在派生对象时进行部分初始化!

一般来说,您需要为此提供一个复制构造函数。赋值操作符类似于复制,但赋值操作实际上是在一个已经构造且可能已经初始化的对象上完成的。

至于你是否做得很好,这取决于你的类的实现细节,其中大部分没有在这里展示。你所展示的看起来不完整。

在尝试实现自己的版本之前,您可能需要考虑使用std::list,直到您更熟悉c++和数据结构。现在,除了出于好奇心或更完整地学习潜在概念之外,很少真正需要重新发明轮子。

你说"一些bug "。问问题的时候提到这些是很有帮助的。

也就是说,看看copyAll的前两行。第一行分配一个新节点,第二行覆盖该指针,永远丢失它。也许你指的是copyList.first = l.first。您还需要在while循环中构造新的节点。