Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <code>delete</code> and not <code>delete[]</code> unless you also used <code>new[]</code>. And finally, <code>delete this</code> is a bad habit, but legal according to the standard. Why don't you just call <code>delete theNode</code> instead of all of this?</p> <p>EDIT: Addressing some comments/additional questions.</p> <p>To allocate a single instance on heap, you use <code>theNode = new Node</code>. The returned pointer must be freed with <code>delete theNode</code>. Calling new will allocate memory and then call <code>Node::Node()</code>, the constructor, so that it can setup it's internal state. Calling delete will call <code>Node::~Node()</code> and then free the allocated memory. The destructor is responsible for cleaning up anything Node uses, but not the memory used by Node itself.</p> <p>To allocate an array of nodes, you use <code>theNodes = new Node[10];</code>. You delete these with <code>delete[] theNodes</code>. Mixing new/delete with new[]/delete[] is undefined behaviour.</p> <p>Placement new is a method where you want to construct an object in <em>already allocated memory</em>. 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) <em>without</em> also freeing the memory allocated for it.</p> <p>Calling <code>delete this</code> is legal in e.g. a <code>Suicide()</code> function, as long as you do not refer to "this" or any members of the deleted instance after the call to <code>delete this</code>. This is a valid technique e.g. in reference counted objects, but is often considered something you should avoid unless you really need it.</p> <p>The correct solution for you is pretty plain, where you now call <code>~Node</code>, simply call <code>delete theNode</code> instead.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload