Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a base class as a safe container for pointers

Tags:

c++

So I was looking at this question Memory Allocation Exception in Constructor where my boss states in his beautiful answer that the destructor will not be called.

Which makes me wonder,

If I were to write

struct XBase
{
    int* a;
    char* b;
    float* c;

    XBase() : a(nullptr), b(nullptr), c(nullptr) {} 
    ~XBase()
    {
        delete[] a; delete[] b; delete[] c;
    }   
};

and

struct X : XBase
{
    X() {
        a = new int[100];
        b = new char[100];
        c = new float[100];
    }
}

Then, if the allocation of c fails (with an exception being thrown), then the destructor of XBase would be called, since the base class has been constructed.

And no memory leak?

Am I correct?

like image 355
P45 Imminent Avatar asked Feb 25 '16 14:02

P45 Imminent


1 Answers

You are right; this will work, because:

  • By the time X constructor body is executed, XBase is already constructed, and its destructor will be called.
  • Doing delete or delete[] on null pointers is perfectly valid, and does nothing.

So, if the allocation of a, b or c fails, the destructor of XBase will deallocate everything.

But, obviously, this design makes you write much more code that needed, since you can simply use std::vector or std::unique_ptr<T[]>.

like image 76
lisyarus Avatar answered Nov 04 '22 11:11

lisyarus