Hello! question about the copy constructor. Wrote a doubly linked list. There were difficulties with the copy constructor. I'll start with destructor. The destructor deletes the memory allocated for each node in the list. Memory is allocated in the constructor (for the head of the list) and in the Insert,PushFront,PushBack . So go to the copy constructor. We need to allocate memory for the node. Next, you need to copy all the pointers to the _next and _prev our copy. But! As soon as the destructor is called for the object from which we copy the data, then all pointers ( _next and _prev ) are destroyed for each node, which means they are not in our copy - hence the error! Tell me how to solve the problem? And is it advisable to do a copy constructor at all? Thank you for attention

  template<class T> class LinkedList { public: struct Node //узел { //// T _value; Node* _next;//указатель на след. узел Node* _prev;//указатель на предыдущий узел }; class Iterator :public std::iterator<std::bidirectional_iterator_tag, T> {//тут все ясно public: //// private: //// }; LinkedList(); ~LinkedList(); LinkedList(const LinkedList& right); Iterator Insert(Iterator wher, T value); Iterator PushFront(T value); Iterator PushBack(T value); /// методы/// } template<class T> LinkedList<T>::~LinkedList() { Iterator begin = Begin(); Iterator end = End(); while (begin != end) { Node* tempNext = begin.GetNext(); delete[]begin.GetNode(); begin = tempNext; } delete[]_head; } template <class T> LinkedList<T>::LinkedList(const LinkedList& right) { _head = new Node[1]; _head->_value = right._head->_value; _head->_next = right._head->_next; _head->_prev = right._head->_prev; } }; 
  • remark: that is, when a destructor is called for a copy, then it tries to clear something that has already been cleared by the destructor of the original and then an error occurs - Artem
  • Your copy constructor should copy nodes, and not save pointers to them. Select new Node[1] and delete delete[] delete[]begin.GetNode(); memory array clearly to anything. - VTT
  • Let it be so, but as soon as the destructor of the original is called, then everything will collapse - Artem
  • As I wrote above, your copy constructor should copy nodes, and not save pointers to them. those. instead of _head->_next = right._head->_next; and _head->_prev = right._head->_prev; It is necessary to go over the list and create a copy of each node. - VTT
  • why this delete [] begin.GetNode (); not necessary?? In methods Insert, PushBack, PushFront memory is allocated dynamically. I have not added a Linked List code to contain more pointers Node * _head, Node * _ptr; in the LinkedList constructor, I allocate memory for the "head" -> next, when adding an element in the Insert methods, .. I allocate memory for the node again - Artem

0