链表运算符 = 移动分配时,将移动所有元素
Linked list operator= When Move Assigning Then All Elements Are Moved
我正在尝试用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;
}
并且您的移动构造函数应该以类似的方式更改。
相关文章:
- 在同一容器中移动元素
- 从标准容器中移动元素是否合法?
- 我可以在 std::list 中移动元素而不会使迭代器或引用无效,但是如何移动呢?
- 在数组中移动元素 SIGABRT 错误
- C++11 在列表到映射(或其他容器)之间移动元素
- 在堆栈中移动元素
- 初始化 std::数组而不复制/移动元素
- 算法,用于查找获取排序列表所需的最小移动元素到结束步骤
- 从Boost Multi_index数组移动元素
- 将一个向量附加到另一个向量时,为什么移动元素比复制它们便宜?
- memmove会移动元素(就像前面的方式相同),还是一次抓住整个内存块
- 在C++数组中移动元素
- 为什么重新分配矢量复制而不是移动元素
- 在矢量中插入元素并在其后移动元素
- 弹出后使用数组>>移动元素排队
- 从STL容器中移动元素是否会将其从该容器中移除
- 对容器进行排序,然后在保留原始排序的情况下移动元素
- 可移动元素向量的大小调整是否有效?
- 我如何构建公共数据,同时保留默认的移动元素和分配
- 扩展std::vector以从其他vector类型移动元素