在C ++中持有int *节点的双向链表上复制赋值运算符深层副本

时间:2017-11-26 17:59:03

标签: c++ copy-constructor deep-copy copy-assignment

我正在尝试实现一个双向链接列表的复制赋值运算符,它正在保存int*节点,但我仍然陷入困境复制而不是分配真实的指针:

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;
    }
}

现在的问题是我仍然指向相同的int* data_,如果我修改了“副本”,我会修改原来的:

ListOfArrays l;
// ... adding some data ...

ListOfArrays copy;
copy = l;
// modifying copy results in modification in the first list

这是我在复制分配复制构建对象时试图实际逃脱的。

0 个答案:

没有答案