Mark
Mark

Reputation: 283

C++ Program crashes when trying to print data from Double Linked List

I am trying to print the data of a node from a double linked list using all shared_ptr, but outputting the data with the print function causes the program to crash. I don't know why it crashes when I try to print it. Could there be something wrong with my Insert function?

template <typename T>
class Node
{
   private:
      T data;
      shared_ptr<Node<T>> next;
      shared_ptr<Node<T>> prev;

   public:
      Node() { next = NULL; prev = NULL; data = 0; }
      Node(T value) { next = NULL; prev = NULL; data = value; }
      T getData() { return data; }
      shared_ptr<Node<T>> getNext() { return next; }
      shared_ptr<Node<T>> getPrev() { return prev; }

};

template <typename T>
class DoubleLinkedList
{
   private:
      shared_ptr<Node<T>> head;
      shared_ptr<Node<T>> tail;
   public:
      DoubleLinkedList()
      {
         head = NULL;
         tail = NULL;
         total = 100;
         for (int i = 0; i < total; i++)
         {
            Insert(objectgetsinsertedhere);
         }
      }

      void print()
      {
         shared_ptr<Node<T>> temp;
         temp = tail;
         temp = temp->getPrev();
         cout << temp->getData().getName();  // getName() is a getter to get the name of the object
      }


      void Insert(T data)
      {
         T value(data);

         if (head == NULL)
         {
            head = make_shared<Node<T>>(data);
            tail = head;
         }
         else
         {
            shared_ptr<Node<T>> nu = make_shared<Node<T>>(data);
            nu->getPrev() = tail;
            if (head == tail)
               head->getNext() = nu;
            tail->getNext() = nu;
            tail = nu;
         }
      }
};

Upvotes: 0

Views: 123

Answers (2)

A. G.
A. G.

Reputation: 9

Do you have a copy constructor defined in your DoubleLinkedList class?

Upvotes: 0

Matthias247
Matthias247

Reputation: 10396

Your assignments in Insert are not doing what you want. These calls:

nu->getPrev() = tail;
if (head == tail)
    head->getNext() = nu;
tail->getNext() = nu;

are all returning a copy the the content of the next and prev fields. The accessors (get/set) create a new shared_ptr object and initialize them with the current value of the prev and next fields. When you reassign the content of these copied shared_ptrs you don't manipulate the state of the node.

So you should either operate on the plain fields (prev and next), return a reference to the fields in the accessor (like shared_ptr>& getNext() { return next; }) or add setter methods for the fields and use those.

Upvotes: 1

Related Questions