how to properly delete `arrayOfPointers**` in C++

Viewed 31

I'm a C++ noob and I'm trying to better understand pointers, specifically arrays of pointers - and in this case using them as an expandable array.

I have the following:

uint8_t thingCount = 0;
Thing **things;

And I add Things to it like this:

void addThing(Thing& thing) 
{
    Thing **newThings = new Thing*[thingCount + 1];
    for (uint8_t i = 0; i < thingCount; i++)
        newThings[i] = things[i];
    delete things;
    things = newThings;

    things[thingCount++] = &thing;
}

and I delete all the Things like this:

deleteAllThings()
{
    for(uint8_t i = 0; i < thingCount; i++)
        delete things[i];
    delete things;
    thingCount = 0;
}

Is this safe and correct, with respect to how I'm handling the pointers?

Is delete both freeing up the memory held by each Thing AND releasing the pointer? Or is the latter not necessary?

Please save your suggestions of using alternative data structures here, this is an exercise in understanding how to use an array of pointers properly. Thanks xx

0 Answers
Related