问题
I am having difficulty figuring out how to implement the rule of 5 in my doubly linked list class. I get the concept of them, it's just lost with how to code it. I have attempted the destructor and copy operator, but at a stand still going forward with the rest. Any help/guidance is appreciated, thanks.
destructor/copy:
~DList() {
Node* current = front_;
while (current != back_)
{
front_ = front_->next_;
delete current;
current = front_;
}
}
// copy ctor
DList(const DList& rhs) {
const Node* current = rhs.front_;
Node* temp = nullptr;
if (current != back_)
{
front_ = new Node(current->data_);
temp = front_;
current = current->next_;
}
while(current != back_)
{
Node* nn = new Node(current->data_);
temp->next_ = nn;
temp = temp->next_;
current = current->next_;
}
}
DList& operator=(const DList& rhs){ //copy assignment // <<---not sure where to begin
List ctor:
DList() {
//Node* front_;
front_ = new Node(); // creating front sentinel
//Node* back_;
back_ = new Node(); // creating back sentinel
//make them point to eachother
front_->next_ = back_;
back_->prev_ = front_;
listSz = 0;
}
Main:
DList<int> list;
DList<int> list2;
DList<int>::const_iterator it;
cout << list.size() << endl;
list.push_front(1);
list.push_front(2);
list.push_back(3);
list.push_front(4);
list.print();
std::cout << endl;
list2.push_front(11);
list2.push_front(12);
list2.push_back(13);
list2.push_front(14);
list2.print();
list2 = list;
list2.print();
回答1:
If you have a working copy constructor (that does not use the assignment operator) and destructor, the assignment operator can simply be this:
#include <algorithm>
//...
DList& operator=(const DList& rhs)
{
DList temp(rhs);
std::swap(temp.front_, front_);
std::swap(temp.back_, back_);
std::swap(temp.listSz, listSz);
return *this;
}
This basically uses the copy / swap idiom. A temporary object is created from the passed in DList, and the internals of the temporary object is swapped out with the internals of the current object. Then the temporary dies off with the old internals.
来源:https://stackoverflow.com/questions/42451647/how-to-implement-an-assignment-operator-in-linked-list-class