Why are the destructor and the copy constructor necessary for the pointer-based implementation of the linked list? Im trying to understand the concept behind it and how it works exactly.
Why are the destructor and the copy constructor necessary for the pointer-based implementation of
Share
It is a question of ownership. Typically linked lists are implemented as sequences of node objects, each of these holding a pointer to the next (and previous, in the case of doubly linked lists) nodes. The list typically holds a pointer to the first node. So when lists are copied, it is necessary to perform a “deep” copy, otherwise the copied list ends up pointing to the same nodes, and you end up with two objects pointing to the same structure. This deep copy is performed by creating a completely new, dynamically allocated, sequence of nodes. This is the reason to implement a copy constructor. It is also necessary to provide an assignment operator following similar logic (see the rule of three). As for the destructor, since each list owns its nodes, and has allocated them dynamically, it must release the resources upon destruction.
In summary: