链表运算符 = 移动分配时,将移动所有元素



我正在尝试用C++编写带衬里的列表,但有些测试失败了。

其中一条说:

GivenNonEmptyCollection_WhenMoveAssigning_ThenAllElementsAreMoved

第二:

GivenNonEmptyCollection_WhenMovingToOther_ThenAllItemsAreMoved

这是我实现运算符= 的方法

LinkedList& operator=(const LinkedList& other)
{
       if(this!=&other)
       {
        while (!isEmpty()) 
          erase(begin());
        for (auto it = other.begin(); it != other.end(); it++)
          append(*it);
      }
return *this;}

第二个:

 LinkedList& operator=(LinkedList&& other)
  {
/* SELF ASSIGNMENT CHECK */
    if(this!=&other)
    {
        while (!isEmpty()) 
        erase(begin());
        while (!other.isEmpty()) 
        {
            append(*(other.begin()));
             other.erase(other.begin());
        }
    }
    return *this;
  }

以下是关于类链表和结构节点的一些内容:

template <typename Type>
class LinkedList
{
    struct Node
    {
        Node* prev;
        Node* next;
        Type* data;
        Node()
        {
            data = nullptr;
            prev = nullptr;
            next = nullptr;
        }
        Node(const Type val)
        {
            data = new Type(val);
            prev = nullptr;
            next = nullptr;
        }
        ~Node()
        {
            prev = nullptr;
            next = nullptr;
            delete data;
        }
    };

private:
    Node *head;
    Node *tail;
    size_type length;
public:
LinkedList(): head(nullptr), tail(nullptr), length(0)
  {
      head = new Node;
      tail = new Node;
      head->next = tail;
      tail->prev = head;
  }

(...)

我不知道这有什么问题。

您正在复制和删除原始列表,但您应该移动它。
在这种情况下,这意味着从另一个列表中"窃取"数据。

它应该看起来更像这样:

LinkedList& operator=(LinkedList&& other)
{
    if(this!=&other)
    {
        // Assuming the existence of 'LinkedList::clear', which empties the list.
        // Replace with the name you chose for that function.
        clear();  
        head = other.head;
        other.head = nullptr;
        tail = other.tail;
        other.tail = nullptr;
        length = other.length;
        other.length = 0;
    }
    return *this;
  }

并且您的移动构造函数应该以类似的方式更改。

最新更新