为什么在重载赋值运算符时未显式复制字段时会自动复制该字段?

时间:2019-04-05 12:52:39

标签: c++ class

我正在为链接列表实现一个类,并在重载该类的赋值运算符时发生了奇怪的事情。我在重载时复制了所有内容。一切正常。现在我注释掉 复制“大小”的代码。它仍然可以正常工作!现在我很困惑。 我用char和std :: string(甚至另一个int)尝试了同样的事情,但是我无法获得魔力。 谁能告诉我为什么? (我使用“大小”字段来跟踪列表的长度。)

#include <string>
#include <iostream>

class LinkedListNode {
public:
    int value;
    LinkedListNode* p_next;
    ~LinkedListNode() {
        delete p_next;
    }
};

class LinkedList {
public:
    LinkedList()
        : size(0), p_head(nullptr)
    {}
    ~LinkedList() {
        delete p_head;
    }

    /* insert a new node at the end of the list with a given value */
    void insert(int value) {
        LinkedListNode* node = new LinkedListNode();
        node->value = value;
        node->p_next = nullptr;

        LinkedListNode* counter = p_head;
        while (true) {
            if (counter == nullptr) {  /* for empty list */
                p_head = node;
                break;
            }
            if (counter->p_next == nullptr) { /* for non-empty list */
                counter->p_next = node;
                break;
            }
            counter = counter->p_next;
        }
        size++;
    }
    int length() {
        return size;
    }
    LinkedList& operator= (const LinkedList& other) {
        // when assigning to itself
        if (this == &other) { return *this; /* to keep the chain assignment alive */ }

        // free the old memory 'cause it's no longer used
        delete p_head;
        p_head = nullptr;

        // copy everything over
        LinkedListNode* counter = other.p_head;
        while (counter != nullptr) {
            insert(counter->value);
            counter = counter->p_next;
        }
        // size = other.size;

        return *this;
    }
    void displayValues() {
        LinkedListNode* counter = p_head;
        while (counter != NULL) {
            std::cout << " " << counter->value << " ";
            counter = counter->p_next;
        }
        std::cout << std::endl;
    }

private:
    LinkedListNode* p_head;
    int size; // and why am I copied automatically??
};
int main() {
    LinkedList first_list;
    first_list.insert(34);
    first_list.insert(56);
    first_list.insert(45);

    std::cout << first_list.length() << std::endl;

    LinkedList second_list;
    second_list = first_list;

    // shoudn't it print 0 ?? Because I didn't copy 'size' field
    // while overloading = operator.
    std::cout << second_list.length() << std::endl;

    std::cin.get();
}

0 个答案:

没有答案