title: Object destroys itself before returning? C++
body: <p>So I did this sorted doubly linked list code. I am supposed to overload a couple of operators. However, when I try to create a new SDL (sorted doubly list) inside one of the functions, it will destroy itself before I manage to return it to the main function. I tried to debug this so many times. I see where the error occurs but I have no clue how to solve it. Here is the code where things mess up.</p>
  
  <pre><code>SortedDoublyLinkedList SortedDoublyLinkedList::operator+(const SortedDoublyLinkedList &amp;    otherList)
  {
      SortedDoublyLinkedList myNewList(otherList);
      Node *currentNode = head;
      while (currentNode) {
          myNewList.add(currentNode-&gt;value);
          currentNode = currentNode-&gt;next;
      }
      return myNewList; // destroys itself
  }
  </code></pre>
  
  <p>Above function will overload when in the main the coder writes "mylist = mylist + mylist2" to add 2 lists together.</p>
  
  <p>Here is another:</p>
  
  <pre><code>SortedDoublyLinkedList SortedDoublyLinkedList::operator+(const int &amp; myNumber)
  {
      SortedDoublyLinkedList myNewList(*this);
      myNewList.add(myNumber);
      return myNewList;    // destroys itself
  }
  </code></pre>
  
  <p>Same deal.</p>
  
  <p>Test cases are these below:</p>
  
  <p>myList += myList2;    // works properly! </p>
  
  <p>myList += myList + 15;    // works properly!</p>
  
  <p>SortedDoublyLinkedList myList3 = myList + 15;    // creates a new list without modifying myList, works properly!</p>
  
  <p>Error occurs when the user types in:</p>
  
  <p>myList = myList + myList2;</p>
  
  <p>myList = myList + 15;</p>
  
  <p>I got no clue why this is happening. Inside the above 2 functions, myNewList will destroy itself before returning, then at the very end of the program, it will try to destroy itself one more time (what?) but since it's already deallocated it will fail destroying it and then an error pops up. </p>