0

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.

wencakisa
  • 5,850
  • 2
  • 15
  • 36
  • `head_ = other.head_;` Is not a deep copy. For a deep copy create a new head and new nodes. Copy the data to the new nodes from the original. – drescherjm Nov 26 '17 at 18:01
  • 1
    Your list class will sooner or later need at least one `insert` function to be useful. Use that. Iterate through the source list and `insert` each value into the destination. There are usually faster ways to do this, but this has the advantage of being dead easy. – user4581301 Nov 26 '17 at 19:47

0 Answers0