title: Implementing a simple singly linked list with smart pointers
body: <p>Hi I'm trying to implement a simple singly linked list using smart pointers, here is what I have so far, I opted with using C++'s shared_ptr but I read that a unique_ptr would be more appropriate for this case but, I don't really know how you would iterate over the list (i.e currentNode = currentNode->next) to get to the end of the list in order to insert an element using a unique_ptr. Here is the code I have so far:</p>
  
  <pre><code>template &lt;typename T&gt;
  class LinkedList;
  
  template &lt;typename T&gt;
  class ListNode
  {
  public:
      ListNode() : _data(T()) {}
      explicit ListNode(const T&amp; value) : _data(value) {}
  
      friend class LinkedList &lt; T &gt; ;
  private:
      T _data;
      shared_ptr&lt;ListNode&lt;T&gt;&gt; _next;
  };
  
  template &lt;typename T&gt;
  class LinkedList
  {
  public:
      void push_back(const T&amp; value)
      {
          if (_root)
          {
              shared_ptr&lt;ListNode&lt;T&gt;&gt; currentNode(_root);
  
              while (currentNode-&gt;_next != nullptr)
              {
                  currentNode = currentNode-&gt;_next;
              }
  
              currentNode-&gt;_next = make_shared&lt;ListNode&lt;T&gt;&gt;(value);
          }
          else
          {
              // If the list is completely empty,
              // construct a new root (first element)
              _root = make_shared&lt;ListNode&lt;T&gt;&gt;(value);
          }
      }
  
      void print() const
      {
          shared_ptr&lt;ListNode&lt;T&gt;&gt; currentNode(_root);
  
          while (currentNode != nullptr)
          {
              cout &lt;&lt; currentNode-&gt;_data &lt;&lt; " ";
              currentNode = currentNode-&gt;_next;
          }
  
          cout &lt;&lt; endl;
      }
  private:
      shared_ptr&lt;ListNode&lt;T&gt;&gt; _root;
  };
  </code></pre>
  
  <p>If using unique_ptrs are the better way to go for this program, could you illustrate how I would get past the iterating problem? Since unique_ptrs can't be assigned, how would I do the code block:</p>
  
  <pre><code>shared_ptr&lt;ListNode&lt;T&gt;&gt; currentNode(_root);
  
  while (currentNode-&gt;_next != nullptr)
  {
      currentNode = currentNode-&gt;_next;
  }
  
  currentNode-&gt;_next = make_shared&lt;ListNode&lt;T&gt;&gt;(value);
  </code></pre>
  
  <p>using unique_ptrs instead of shared_ptrs? Thanks!</p>