I am a computer science student with the task of creating a dynamic data structure, linked lists. I am currently working on a singly linked list and have successfully built the functionality to add, remove and dump all node data.
However, remembering that my ‘advanced programming’ lecturer stated that in order to avoid confusion and other problems, when deleting nodes from a list, or releasing any object’s memory, you should have it happen inside its deconstructor. So I moved:
delete[] _del;
Which worked fine and moved it to the nodes’ deconstructor:
#include "Node.h"
// Node.cpp
Node::Node(const int &inData, const int &inId)
{
_id = inId;
_data = inData;
nextNode = NULL;
}
// Deconstructor to delete the node when using List.Del()
Node::~Node()
{
delete[] this;
}
In my List the node’s deconstructor is called via a pointer like so:
_del->~Node();
Which gives me an assertion error. I’m assuming it is my usage of ‘this’ in the node’s deconstructor?
Thanks for your time.
First of all, you should not call an objects destructor directly, unless you’re writing an allocator and used placement new when creating it. Second, you should
deleteand notdelete[]unless you also usednew[]. And finally,delete thisis a bad habit, but legal according to the standard. Why don’t you just calldelete theNodeinstead of all of this?EDIT: Addressing some comments/additional questions.
To allocate a single instance on heap, you use
theNode = new Node. The returned pointer must be freed withdelete theNode. Calling new will allocate memory and then callNode::Node(), the constructor, so that it can setup it’s internal state. Calling delete will callNode::~Node()and then free the allocated memory. The destructor is responsible for cleaning up anything Node uses, but not the memory used by Node itself.To allocate an array of nodes, you use
theNodes = new Node[10];. You delete these withdelete[] theNodes. Mixing new/delete with new[]/delete[] is undefined behaviour.Placement new is a method where you want to construct an object in already allocated memory. In this case, you have the only good reason for calling a destructor directly, you want to deconstruct an object (aka letting it clean itself up) without also freeing the memory allocated for it.
Calling
delete thisis legal in e.g. aSuicide()function, as long as you do not refer to “this” or any members of the deleted instance after the call todelete this. This is a valid technique e.g. in reference counted objects, but is often considered something you should avoid unless you really need it.The correct solution for you is pretty plain, where you now call
~Node, simply calldelete theNodeinstead.