Im a little confused on how to implement an copy assignment on a doubly linked List. I managed to get the copy constructor working but im sure on the assignment. Im trying to do this without the copy and swap method.
List.H
class List
{
public:
List();
~List();
List(const List& c);
List& operator= (const List& t);
private:
List *Next;
List *Prev;
Node *Head;
List.cpp
List::~List()
{
Node* move = Head;
while (move!=NULL)
{
Node *temp = move->Next;
delete move;
move = temp;
}
}
List::List(const List& c)
{
name = c.name;
Prev = c.Prev;
Next = c.Next;
Node* dummy, * current;
Head= dummy = new Node();
current = c.Head;
while (current)
{
dummy->Next = new Node(*current);
current = current->Next;
dummy = dummy->Next;
}
Node* temp = Head;
Head = Head->Next;
delete temp;
}
List& List::operator=(const List& t)
{
Next = t.Next;
return *this;
}
Would I also have to traverse each node in the assignment operator as well?
Edit So this is what I have now. The problem is when im getting the data from the list it is null.
List& List::operator=(const List& that)
{
if (this != &that)
{
while (Head)
{
Node* temp = Head;
Head = Head->Next;
delete temp;
}
Node* dummy, * current;
Head = dummy = new Node();
current = that.Head;
while (current)
{
dummy->Next = new Node(*current);
current = current->Next;
dummy = dummy->Next;
}
dummy->Next = nullptr;
}
return *this;
}
copy-ctorandoperator=both are doing shallow copy. Which will can lead to undefined behavior due todeleteing same memory from two different objectsPrevandNextwhatever they are, are not deep-copied, but they are also not deleted in the destructor, so it should be fine.NextandPrevious. @Jay any explanation forNextandPrevioususecase?