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; } };
new Node[1]and deletedelete[] delete[]begin.GetNode();memory array clearly to anything. - VTT_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