c++ – allocating memory in a class method

Question:

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. is it legal to allocate memory for _ptr not in the constructor but in the method? while in the destructor to free memory? 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;
}

Answer:

In the general case, yes, quite. 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 you call it, you get a leak. Why do you even allocate memory as new Node[1] and not just new Node ?

And hopefully the copy constructor and assignment operator are written correctly (or not allowed)?

Scroll to Top