C++ language questions

Topics


Destructors

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; }
}
  1. If the destructors had no code, i.e., Bar::~Bar() {} and Foo::~Foo() {}, what would things look like after
        Foo* f = new Foo();
        delete f;
    
  2. If the Foo destructor were
    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;   
    
  3. If the Foo destructor were
        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;   
    
  4. Why does the following Foo destructor possibly cause a core dump?
        Foo::~Foo() { 
            delete[] iarray; 
            delete[] barray;
            for (i=0; i < 10; i++) if (barray[i]) delete barray[i];
        }
    
  5. If the Foo destructor were
        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;   
    
  6. Assume the destructor for Foo in 5. Would everything be deleted in the after executing the following:
        Foo* f = new Foo();
        f->barray[0] = new Bar();
        f->barray[1] = new Bar();
        f->barray[0]->fptr = new Foo();
        delete f;   
    
  7. In the example above what happens if the Bar destructor is:
        Bar::~Bar()
        {
            if (fptr != NULL) delete fptr;
        }
    
    Would everything be deleted?
  8. Finally, what is the difference between deleting allocated memory when there is a constructor for the type and when there isn't.

Answers.


C++ language / Review questions / 15-211 A, B