template<class T> class LinkedList { public: struct Node //узел { public: ... private: T _value; Node *_next; Node *_prev; }; class Iterator :public std::iterator<std::bidirectional_iterator_tag, T> { public: ... private: Node *node; ... }; private: Node *_head; Node *_ptr; }; 

Hello. The question is this. is it legal to allocate memory for _ptr not in the constructor but in the method? thus in memory to release? like this:

  template<class T> LinkedList<T>::LinkedList() { _head = new Node[1]; _ptr = nullptr; _head->_value = T(); _head->_next = nullptr; _head->_prev = nullptr; } template<class T> LinkedList<T>::~LinkedList() { delete[]_head; delete[]_ptr; } template<class T> typename LinkedList<T>::Node *LinkedList<T>::getPtr(T value, Node *next, Node* prev) { _ptr = new Node[1]; _ptr->_value = value; _ptr->_next = next; _ptr->_prev = prev; return _ptr; } 
  • one
    use smart pointers. - Abyx
  • don't allocate arrays from one element, it doesn't make sense - Abyx
  • Can you show how smart pointers to use in my code? I will be grateful - Artem
  • replace Node* with shared_ptr<Node> , for example - Abyx
  • for smart pointers (and for containers), the memory in the destructor does not need to be freed, right? - Artem

1 answer 1

In general, yes, completely. The main thing is that your object is in a normal state after the constructor.

But! How did you decide that your getPtr will be called exactly once? And the second time you call it you will get a leak. Why do you allocate memory as new Node[1] , and not just new Node ?

And, I hope, the copy constructor and the assignment operator are written correctly (or are forbidden)?