Franken Steak Franken Steak - 7 months ago 33
C++ Question

What all should be deleted in the destructor of a class

So it's been a while since I've done any c++ coding and I was just wondering which variables in a basic linked list should be deleted in the destructor and unfortunately I can't consult my c++ handbook at the moment regarding the matter. The linked list class looks as follows:

#include <string>
#include <vector>

class List
List *next;
string sName;
vector<char> cvStuff;

List(string _s, int _i)
next = nullptr;
sName = _s;

for (int i = 0; i < _i; i++)
cvStuff.insert(cvStuff.end(), '_');

//since sName is assigned during runtime do I delete?
//same for cvStuff?

I'm also curious, if in the destructor I call

delete next;

will that go to the next node of the linked list and delete that node and thus kind of recursively delete the entire list from that point? Also, if that is the case and I choose for some reason to implement that, would I have to check if next is nullptr before deleting it or would it not make a difference?

Thank you.


Basically you should just

delete next 

and that's all you should do:

  • The string and vector objects have their own destructors, and since this object is being destructed, theirs will be called.

  • Deleting a null pointer is not a problem, so you don't even have to check for that.

  • If next is not a null pointer, it will keep on calling the destructors of the next nodes, on and on, as needed.

Just delete it and that's all, then.