c++ - Assertion failure: calling a list's node deconstructor -
i computer science student task of creating dynamic data structure, linked lists. working on singly linked list , have built functionality add, remove , dump node data.
however, remembering 'advanced programming' lecturer stated in order avoid confusion , other problems, when deleting nodes list, or releasing object's memory, should have happen inside deconstructor. moved:
delete[] _del;
which worked fine , moved nodes' deconstructor:
#include "node.h" // node.cpp node::node(const int &indata, const int &inid) { _id = inid; _data = indata; nextnode = null; } // deconstructor delete node when using list.del() node::~node() { delete[] this; }
in list node's deconstructor called via pointer so:
_del->~node();
which gives me assertion error. i'm assuming usage of 'this' in node's deconstructor?
thanks time.
first of all, should not call objects destructor directly, unless you're writing allocator , used placement new when creating it. second, should delete
, not delete[]
unless used new[]
. , finally, delete this
bad habit, legal according standard. why don't call delete thenode
instead of of this?
edit: addressing comments/additional questions.
to allocate single instance on heap, use thenode = new node
. returned pointer must freed delete thenode
. calling new allocate memory , call node::node()
, constructor, can setup it's internal state. calling delete call node::~node()
, free allocated memory. destructor responsible cleaning node uses, not memory used node itself.
to allocate array of nodes, use thenodes = new node[10];
. delete these delete[] thenodes
. mixing new/delete new[]/delete[] undefined behaviour.
placement new method want construct object in already allocated memory. in case, have reason calling destructor directly, want deconstruct object (aka letting clean up) without freeing memory allocated it.
calling delete this
legal in e.g. suicide()
function, long not refer "this" or members of deleted instance after call delete this
. valid technique e.g. in reference counted objects, considered should avoid unless need it.
the correct solution pretty plain, call ~node
, call delete thenode
instead.
Comments
Post a Comment