gardian06
gardian06

Reputation: 1546

removing objects from an array

I am creating a program that uses an array of objects declared with

Element * elements = new Element[number];

where an element is a class that has/needs a its own destructor.

when I go to delete this would I use just use array delete, and have the program worry about calling the destructor:

delete [] elements;

or do I call the destructor for each item explicitly with keyword delete:

for(int ii = 0; ii< ArraySize; ii++)
    delete elements[ii];
delete [] elements;

Note: I understand that I could probably use something like boost::ptr_vector, but I wanted similar to hashTable functionality (so the for loop would need additional information, but that is outside of the direct scope of this question) which is why I am using a traditional array. I would still like to know which behavior is needed to avoid memory leaks.

Upvotes: 1

Views: 4064

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490108

Yes, delete [] elements; should be sufficient.

You'd use your second piece of code with something like:

Element **elements;

elements = new Element *[rows];
for (int i=0; i<rows; i++)
    elements[i] = new Element;

This combination rarely makes much sense though. To make at least some sense, each row would itself be a dynamically allocated array as well:

elements = new Element *[rows];
for (int i=0; i<rows; i++)
    elements[i] = new Element[row_len];

In this case, your deletion would look something like:

for (int i=0; i<rows; i++)
    delete [] elements[i];
delete [] elements;

As you're doing it right now, however, none of what you've said really justifies home-rolled dynamic allocation at all. std::vector<Element> elements(number); would work perfectly well.

Upvotes: 1

Cornstalks
Cornstalks

Reputation: 38218

The first one. You should

delete [] elements;

The second one is incorrect and should give you errors if you try to compile it.

Upvotes: 3

Related Questions