0

In a linked list class, the code below is declaring Node<T> *newNode:

void LinkedList<T>::push_front(const T& val) {
    Node<T> *newNode = new Node<T>(val);
    newNode->next = head;
    head = newNode;
    if(newNode->next == NULL) tail = newNode;
}

Why do we use dynamic allocation? Can't we just write Node<T> newNode(val);?

I think since we are not making arrays of newNode, it is valid.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • I think we can aslo change the following codes : newnode->next to newnode.next – user18926955 Apr 24 '22 at 07:28
  • the list store a pointer to a Node, the object pointed has to be "valid" for the lifetime of the list. If you store a pointer to a local variable, destroyed at the end of the function, you are storing a pointer to an object which will be invalid soon, much before the list lifetime ends – Gian Paolo Apr 24 '22 at 08:07

1 Answers1

1

A local variables such as Node<T> newNode(val); would be destroyed when exiting the function (or rather, when exiting the scope (aka braces, more or less)) that it was created in.

But for a linked list, you want the nodes to live longer; as long as you want them to.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207