I am already able to do a Linked-List with smart pointers, which means in this particular case that I can use std::unique_ptr. However, I wanted to try with raw ones for learning purposes.
So far, I am having a memory leak, and it's coming from line 47 in the insert function. How can I fix it? I was thinking to just plug a destructor ~Link(){delete next;} in the Link struct, so when a Link goes out of scope in a function, then its is automatically destroyed, but I don't know if this is the right choice. (Notice that I also deleted first, my head, in ~List )
I'd like to understand how I can fix this. Even other workarounds are much appreciated.
I updated my code in this way: notice the destructor of List at line 31: please tell me if I am doing precisely what you meant. I have seen that so far I have no memory leaks.
~List()
{
auto it = begin();
while (it != this->end())
{
delete it.current;
++it;
}
}
I don't think so. ++it does current = current->next - but you're just deleted current!
You need to get the address of the next node before you delete the memory of the current one. Without using iterators, the usual code would be something like:
1 2 3 4 5 6
while (head != nullptr) {
constauto cur {head};
head = head->next;
delete cur;
}
Thanks @seeplus, I've understand the issue now. I have just written the following destructor, but using iterators now. I think it's doing the same thing you wrote in your last snippet. Do you agree? After this check, I can consider the topic closed :-)
1 2 3 4 5 6 7 8 9
~List(){
auto it = begin();
while (it!=nullptr)
{
constauto current_node = it.current;
++it;
delete current_node;
}
}
Ah yes, that for loop is really the classical way to traverse a container... don't know why I wrote that while. Btw, thanks a lot for your help @seeplus