What exactly should go into a destructor.

Feb 7, 2012 at 5:22pm
Hi,

I have two classes, one is for a directory, and another for a file. Directory class, has this data member (alongside others):
1
2
private:
    set<file *> files;

and this member function:
1
2
3
4
5
void directory::addFile(string filename)
{
    temp = new file(filename,this); // second argument indicates parent for file.
    files.insert(temp);
}

Here is what I wrote as a destructor:
1
2
3
4
5
6
7
8
9
directory::~directory ()
{
    set<file *>::iterator pos;
    for (pos = files.begin(); pos != files.end(); ++pos)
    {
        delete (*pos); // delete file object
    }
    delete [] &files; // delete set of pointers.
}

My question is: is this a correct approach. And another question, should I also delete other data members, namely:
1
2
    string name;
    directory *parent;

They both are set inside constructor. I am wondering if they get deleted automatically or not.
Feb 7, 2012 at 5:26pm
Line 8 is incorrect! You should NEVER delete something you didn't allocate with new.

The destructors of those other objects will be called automatically just as their constructors were called automatically. Also you don't call the destructors explicitly unless you used placement new.
Last edited on Feb 7, 2012 at 5:28pm
Feb 7, 2012 at 5:30pm
Ohh, I see. Thanks.
Feb 7, 2012 at 5:48pm
If you allocate memory for directory * parent in your constructor then yes you need to free/delete in your deconstructor. As a side note, I tend to er on the side of safety and check my pointers before deleting them, this will save you headache in the future...

e.g.
1
2
if(*pos)
   delete (*pos);


And to clarify, standard containers will automatically call the deconstructor, but it will not deallocate memory that was allocated for that object so you do need to free that memory like you have.

As L B said, line 8 is incorrect. files is just a std::set which will cleanup itself.

Lets say your set was this instead:
1
2
3
//...

std::set<file> * files;


Your deconstructor would look something like this...
1
2
3
4
5
6
7
8
9
10
11
//...
//... No loop, deconstructors for each file object called automatically...
//...

if(files)
{
   delete (files);
   files = NULL;
}
//...
Feb 7, 2012 at 6:02pm
clanmjc, delete does nothing if the pointer is 0.
Feb 7, 2012 at 6:32pm
duly noted, I guess it's out of habit before using a pointer and to indicate if there might be a bug.
Topic archived. No new replies allowed.