I am trying to implement a copy assignment operator of a doubly linked list which is holding nodes of int*
, but I am stuck with making a deep copy and not assigning the real pointers:
class ListOfArrays {
struct ArrayNode {
int* data_;
int size_;
ArrayNode* prev_;
ArrayNode* next_;
ArrayNode(int* data, int size)
: data_(data), size_(size), prev_(0), next_(0)
{}
~ArrayNode() {
delete [] data_;
}
};
int size_;
ArrayNode* head_;
public:
ListOfArrays()
: size_(0), head_(new ArrayNode(0, 0))
{
head_->prev_ = head_->next_ = head_;
}
ListOfArrays(const ListOfArrays& other)
: size_(other.size_), head_(other.head_) {
head_->prev_ = other.head_->prev_;
head_->next_ = other.head_->next_;
}
ListOfArrays& operator=(const ListOfArrays& other) {
if (this != &other) {
delete head_;
size_ = other.size_;
head_ = other.head_;
// I am confused what to actually do here
head_->prev_ = other.head_->prev_;
head_->next_ = other.head_->next_;
}
return *this;
}
}
The problem now is that I am still pointing to the same int* data_
and if I modify the "copy", I modify the original one:
ListOfArrays l;
// ... adding some data ...
ListOfArrays copy;
copy = l;
// modifying copy results in modification in the first list
This is what I am trying to actually escape while copy assigning or copy constructing the object.