As others have pointed out, you are returning a reference to a local variable, which is undefined behavior.
Since you're passing the object in your assignment operator by value, this indicates that you have written a working copy constructor and destructor for your linked list class. If the copy constructor and destructor are not working or not completed, then right away, your code is broken even before the return
statement.
But if we are to assume that your copy constructor and destructor are implemented, working, and have no bugs, here is an easier way to write your assignment operator:
LList<T>& LList<T>::operator=(LList s){
std::swap(s.head_, head_);
std::swap(s.length, length);
// swap out any other members
return *this;
}
I don't know your other member variables, so you need to swap those also. Basically all we do is take the list you passed by value (again, this could only work if your copy constructor is working), and swapped out the internals of s
with the current object. Then when s
dies (which is why you must have a working destructor for LList
), it takes along with the old data, while the new data sits in this
.
Then we return *this
, which is what you should have returned in your initial attempt, and not a reference to a local variable.
Look up the copy/swap
idiom for writing assignment operators.