Created
June 15, 2021 15:22
-
-
Save BogdanAriton/569292a4af2a3cc5053684de556fcddb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// copy constructor | |
LinkedList(const LinkedList &other) noexcept | |
{ | |
// the copy constructor will have to go through all the nodes in other and make a copy of them into our list | |
// for that we need to be able to add the new nodes to this list, basically we need to copy the data and recreate the links | |
std::cout << "*** Copy constructor ***" << '\n'; | |
if (other.head == nullptr) | |
return; | |
head = std::make_unique<Node>(other.head->data); // we need to know who head is - thus it needs to be initialized separately | |
Node *current = head.get(); | |
size = 1; | |
Node *otherCurrent = other.head->next.get(); | |
while (otherCurrent != nullptr) | |
{ | |
current->next = std::make_unique<Node>(otherCurrent->data); | |
otherCurrent = otherCurrent->next.get(); | |
current = current->next.get(); | |
size++; | |
} | |
} | |
// copy assignment operator | |
LinkedList &operator=(const LinkedList &other) noexcept | |
{ | |
std::cout << "*** Copy assignment operator ***" << '\n'; | |
LinkedList tempList(other); | |
head.swap(tempList.head); | |
std::swap(size, tempList.size); | |
return *this; | |
} | |
// move constructor | |
LinkedList(LinkedList &&other) noexcept | |
{ | |
std::cout << "*** Move constructor ***" << '\n'; | |
head.swap(other.head); | |
size = other.size; | |
other.head = nullptr; | |
other.size = 0; | |
} | |
// move assignment operator | |
LinkedList &operator=(LinkedList &&other) noexcept | |
{ | |
std::cout << "*** Move assignment operator ***" << '\n'; | |
this->clear(); | |
head.swap(other.head); | |
size = other.size; | |
other.head = nullptr; | |
other.size = 0; | |
return *this; | |
} | |
// nodes are managing their own memory using unique_ptr | |
~LinkedList() noexcept {}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment