I am writing a doubly linked list class, and I have a need to overload operator =. Piece of class
template<class T> class List : public Collection<T> { private: class Node { public: Node *_next; Node *_prev; T _data; }; Node *_head; Node *_tail; public: List() : _head(nullptr), _tail(nullptr) {} List(const T arr[]){ for(const T &n: arr) this->push_back(n); } List(const List & copy): _head(nullptr), _tail(nullptr) { Node *temp = copy._head; while (temp != nullptr) { push_back(temp->_data); temp = temp->_next; } } ~List() { while (_head) { _tail = _head->_next; delete _head; _head = _tail; } } List<T> & operator=(const List & l){ this->~List(); Node *temp = l._head; while (temp != nullptr) { push_back(temp->_data); temp = temp->_next; } return *this; } void push_back(const T &data) { Node *newNode = new Node; newNode->_data = data; newNode->_next = nullptr; if (is_empty()) { newNode->_prev = nullptr; _head = _tail = newNode; } else { newNode->_prev = _tail; _tail->_next = newNode; _tail = newNode; } } }; As you can see, the method body is copied from the copy constructor. I did not find a simpler way to replace the list (I can’t call the copy constructor over this object and then return it to it?). If you tell me how to shorten this operator (if possible), I will also be grateful?
push_back, where is the declaration of the class itself? Why copy the body of a method from a copy constructor at all? Make two methods -clearandappend- VTT