Before anything else: I really, really hope this is homework assigned to you in order to understand a doubly linked list. Otherwise there is no reason to use this instead of std::list
. With this out of the way:
No, delete this
in a dtor is always wrong, as the dtor is called when this
is in the state of being deleted.
Also, while
delete temp;
temp = temp->next();
incidentally might work, it's certainly wrong, since, where you attempt to access temp->next()
, temp
is already deleted, so you should call a member function on it. Doing so invokes so-called "undefined behavior". (In short: It might do what you want, but it might just as well fail always or sporadically or only when Friday, 13th, collides with new moon. It migh also invoke very nasty nasal demons on you.)
Note that you could solve both problems by deleting the next node in your node's dtor:
Node::~Node()
{
delete next();
}
That way, your list dtor becomes very easy, too:
DoublyLinkedList::~DoublyLinkedList()
{
delete first();
}
To me, this seems what dtors were invented for, so, except for the fact that nobody should write their own linked list types anymore nowadays, to me this seem to be the C++ solution to your problem.