简体   繁体   English

如何创建深拷贝构造函数?

[英]How to create deep copy constructor?

I have this code, and I have to create a copy constructor for it to create a deep copy of the passed object.我有这段代码,我必须为它创建一个复制构造函数来创建传递的 object 的深层副本。 How can I create that?我怎样才能创造它?

template<typename T>
class SSL {
    struct Node {
        T data;
        Node* next;
    };
    Node* head = nullptr;
public:
    // ...
};

You simply need to iterate the source object's list, making new nodes that have copies of its data, eg:您只需要迭代源对象的列表,创建具有其数据副本的新节点,例如:

template <typename T>
class SSL {
    struct Node {
        T data;
        Node* next = nullptr;
        Node(const T &value) : data(value) {}
    };

    Node* head = nullptr;

public:
    // ...

    SSL() = default;

    SSL(const SSL &src) {
        Node **n = &head;
        for (Node *cur = src.head; cur; cur = cur->next) {
            *n = new Node{cur->data};
            n = &(n->next);
        }
    }

    SSL(SSL &&src) : head(src.head) {
        src.head = nullptr;
    };

    ~SSL() {
        Node *cur = head;
        while (cur) {
            Node *n = cur;
            cur = cur->next;
            delete n;
        }
    }

    SSL& operator=(SSL rhs) {
        std::swap(head, rhs.head);
        return *this;
    }

    // ...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM