I've been using C for about a year and finally decided to learn C++. I'm trying to implement my own linked list class like this:
#include <cstdio>
#include <cstdlib>
struct linked_list_node
{
int value;
struct linked_list_node* next;
};
class LinkedList
{
linked_list_node* head;
public:
LinkedList add(int value)
{
printf("add called\n");
if (head == nullptr)
{
head = new linked_list_node;
head->value = value;
head->next = nullptr;
}
else
{
linked_list_node* curr = head;
while (curr->next != nullptr) curr = curr->next;
curr->next = new linked_list_node;
curr->next->value = value;
curr->next->next = nullptr;
}
return *this;
}
int get(size_t index)
{
linked_list_node* curr = head;
for (int i = 0; i < index; i++) curr = curr->next;
return curr->value;
}
LinkedList()
{
head = nullptr;
}
~LinkedList()
{
linked_list_node* curr = head, * temp;
while (curr != nullptr)
{
temp = curr;
curr = curr->next;
delete temp;
}
}
};
int main()
{
LinkedList l;
l.add(1);
l.add(2);
printf("%d\t%d\n", l.get(0), l.get(1));
return 0;
}
This causes an exception to occur. I've found the mistake, which was the method add
returning *this
. This caused the destructor to be called after l.add(1)
, which deleted the allocation for head
and screwed up the whole program. After defining the add
method as:
void add(int value) // void method
{
printf("add called\n");
if (head == nullptr)
{
head = new linked_list_node;
head->value = value;
head->next = nullptr;
}
else
{
linked_list_node* curr = head;
while (curr->next != nullptr) curr = curr->next;
curr->next = new linked_list_node;
curr->next->value = value;
curr->next->next = nullptr;
}
// doesn't return *this
}
the code ran flawlessly. Can someone please explain why returning *this
causes the destructor to get called. Thanks in advance :)