views:

135

answers:

5

I have a class that creates a vector of objects. In the deconstructor for this class I'm trying to deallocate the memory assigned to the objects. I'm trying to do this by just looping through the vector. So, if the vector is called maps I'm doing:

Building::~Building() {
    int i;
    for (i=0; i<maps.size(); i++) {
        delete[] &maps[i];
    }
}

When I run this the program seg faults while deallocating memory. I think what I'm doing is actually deleting the array storing the objects and not the objects themselves. Is this correct? If not any ideas as to what I'm doing wrong? Thanks.

A: 

If you're using std::vector then you can just let it get handled by the destructor for vector, assuming there are "objects" (and not pointers to objects) in said vector.

-- or --

If you're using a standard array as the "vector":

The purpose of the "delete []" variation is to deallocate an entire array, and hence avoid the need to have a for loop like you do.

If using standard C/C++ arrays, "delete [] maps" should do it for you. "[]" shouldn't be used for deallocating STL vectors.

John Carter
-1 because he is not really talking about arrays here. Deleting a std::vector that way is really a bad idea, apart from not really being applicable. After the edit, still -1 for suggesting to manually call the destructor - which is also a pretty bad idea, seeing as it will most likely get called again when the object goes out of scope. The vector can be emptied via `swap` if needed, though, but even that is seldom necessary.
Jim Brissom
You're right, I didn't mean to suggest calling the destructor explicitly.
John Carter
+7  A: 

It depends on how vector is defined.

If maps is a vector<myClass*> you delete each element with something similar to:

for ( i = 0; i < maps.size(); i++)
{
    delete maps[i];
}

If maps is a vector<myClass> I don't think you need to delete the individual elements.

Alex Reece
This is only half of the story. You can allocate the pointer as you are saying yet still do it wrong. This is the thrust of what I was getting at in my post. Certainly you are correct, but understanding the types is the easy part (he's already figured half of it out) because the compiler tells you. It seems to me that he has a slight misunderstanding of memory management fundamentals.
San Jacinto
Thats a very good point. Your answer is excellent.
Alex Reece
+2  A: 
San Jacinto
+1  A: 

It's hard to tell from the terminology you've used and the code presented exactly what's going on. So maybe a few examples would help you out.

Array new and array delete

What's up with new [] and delete [] you ask? These guys are used for allocating/deallocating arrays of things. Those things could be POD or they could be full fledged objects. For objects they will call the constructor after allocating and destructor while deallocating.

Let's take a contrived example:

class MrObject
{
public:
   MrObject() : myName(new char[9]) { memcpy(myName, "MrObject", 9); }
   virtual ~MrObject() { std::cout << "Goodbye cruel world!\n"; delete [] myName; }
private:
   char* myName;
};

Now we can do some fun stuff with MrObject.

Arrays of objects

First let's create a nice and simple array:

MrObject* an_array = new MrObject[5];

This gives us an array of 5 MrObjects, all nicely initialized. If we want to delete that array we should perform an array delete, which in turn will call the destructor for each MrObject. Let's try that:

delete [] an_array;

But what if we goofed up and just did a normal delete? Well now's a good time to try it for yourself

delete an_array;

You'll see that only the first destructor get's called. That's because we didn't delete the whole array, just the first entry.

Well sometimes. It's really undefined what happens here. The takeaway is to use the array form of delete when you use an array new, ditto for just plain old new and delete.

Vectors of Objects

OK, so that was fun. But let's take a look at the std::vector now. You'll find that this guy will manage the memory for you, and when he goes out of scope, well so does everything he's holding onto. Let's take him out for a test ride:

std::vector<MrObject> a_vector(5);

Now you have a vector with 5 initialized MrObjects. Let's see what happens when we clear that sucker out:

a_vector.clear();

You'll note that all 5 destructors got hit.

Vectors of Pointers to Objects

Oooooh you say, but now lets get fancy. I want all the goodness of the std::vector, but also want to manage all the memory myself! Well there's a line for that as well:

std::vector<MrObject*> a_vector_of_pointers(5);
for (size_t idx = 0; idx < 5; idx++) {
   // note: it's just a regular new here, not an arra
   a_vector_of_pointers[idx] = new MrObject;
}

See that was a bit more of a pain. But it can be useful, you could use a non-default constructor when creating MrObject. You could put derived MrObjects in there instead. Well as you can see the sky's the limit. But wait! You created that memory, you best manage it. You'll want to loop over each entry in the vector and cleanup after yourself:

for (size_t idx = 0; idx < a_vector_of_pointers.size(); idx++) {
   delete a_vector_of_pointers[idx];
}
Eric Rahm
Using `delete` on something obtained from `new[]` is undefined behaviour I think; in many cases only the first constructor is called but it is also legal behaviour for the application to erase your hard drive.
dreamlax
In other cases, the compiler guesses your mistake and deletes everything. Who knows what will happen! it's always a surprise!. Use `delete[]`!
TokenMacGuy
So true, I should have said: this is bad, don't do it! I'll clear that up.
Eric Rahm
A: 

It's hard to say from your question just what the signature of maps is. I'm guessing you want to use delete[] because you also used new[]. So does that mean the members of your vector is itself a collection? supposing it is, then you have something like this:

class Building {
  public:
    typedef int* maps_t;
  private:
    std::vector<maps_t> maps;
  public:
    Building();
    ~Building();
};

Building::Building(size_t num_maps) {
  for(;num_maps; --num_maps)
  {
    maps.push_back(new Building::maps_t[10]);  
  }
}

in that case, your destructor is nearly right; you need change only &maps[i] to maps[i].

Building::~Building() {
    int i;
    for (i=0; i<maps.size(); i++) {
        delete[] maps[i];
    }
}

But in C++, we rarely like to do things that way. For one thing, unless you are actually trying to implement something like std::vector, you rarely want to use new[] or delete[] explicitly. You can, for example, use std::vector. You need perform no explicit memory management in that case. Your class will look like so:

class Building {
  public:
    typedef std::vector<int> maps_t;
  private:
    std::vector<maps_t> maps;
  public:
    Building();
};

Building::Building(size_t num_maps) {
  for(;num_maps; --num_maps)
  {
    maps.push_back(Building::maps_t(10));  
  }
}

There is no user defined destructor in this case, because std::vector already manages its own memory quite well.

TokenMacGuy