I am studying for a final tomorrow in a c++ class, and one thing that I was thinking about while studying was what happens to assigned-to object data after a copy/move assignment overload is called.
Say we have this class:
class linked_list {
public:
//You need to implement this part.
int num_nodes;
node * head;
linked_list() { num_nodes = 0; head = nullptr; }
~linked_list(); //dectructor
linked_list(const linked_list &other); //copy constructor
void operator=(linked_list &other); //copy assignment overload
linked_list(linked_list &&other); //move constructor
void operator=(linked_list &&other); //move assignmend overload
};
I realized that throughout the whole semester I've been just copying in/taking ownership of the other data, without ever worrying about the previous data in the assigned-to object.
void linked_list::operator=(linked_list &other) { //copy assignment overload
num_nodes = 0;
head = nullptr;
node * n = other.head;
while (n != nullptr) {
push_back(n->value);
n = n->next;
}
}
void linked_list::operator=(linked_list &&other) { //move assignment overload
num_nodes = other.num_nodes;
head = other.head;
other.head = nullptr;
}
With the two examples that I have here, wouldn't the data of all the nodes in the current (this) linked_list still be floating around in memory? Before doing my copying/moving, would I have to iterate through the entire current linked list and delete each node?
For some reason I get the vibe from both other students and the course material that the class destructor is implicitly called before entering the two overloaded functions, because NOWHERE do I ever see any mention about having to free up current data first.
Any clarification would be extremely helpful.
Thank you,