I have this code, and I have to create a copy constructor for it to create a deep copy of the passed 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;
}
// ...
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.