The following is a post written by Seth Goldstein that included number of good questions about destructors.
Think about the following examples to get a handle on what a destructor should and shouldn't do. Assume the following definitions:
class Bar {
public:
class Foo* fptr;
Bar();
~Bar();
other stuff
};
class Foo {
public:
int* iarray;
class Bar** barray;
Foo();
~Foo();
other stuff
};
Bar::Bar()
{
fptr = NULL;
}
Foo::Foo()
{
barray = new Bar[10];
iarray = new int[10];
for (int i=0; i < 10; i++) { barray[i] = NULL; iarray[i] = 0; }
}
Foo* f = new Foo();
delete f;
Foo::~Foo() {
delete[] iarray;
delete[] barray;
}
What would things look like after
Foo* f = new Foo();
f->barray[0] = new Bar();
f->barray[1] = new Bar();
delete f;
Foo::~Foo() {
delete[] iarray;
for (i=0; i < 10; i++) if (barray[i]) delete barray[i];
}
What would things look like after
Foo* f = new Foo();
f->barray[0] = new Bar();
f->barray[1] = new Bar();
delete f;
Foo::~Foo() {
delete[] iarray;
delete[] barray;
for (i=0; i < 10; i++) if (barray[i]) delete barray[i];
}
Foo::~Foo() {
delete[] iarray;
for (i=0; i < 10; i++) if (barray[i]) delete barray[i];
delete[] barray;
}
What would things look like after
Foo* f = new Foo();
f->barray[0] = new Bar();
f->barray[1] = new Bar();
delete f;
Foo* f = new Foo();
f->barray[0] = new Bar();
f->barray[1] = new Bar();
f->barray[0]->fptr = new Foo();
delete f;
Bar::~Bar()
{
if (fptr != NULL) delete fptr;
}
Would everything be deleted?