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
for(std::vector<MyObjectClass>::iterator beg = myVector->begin(), end = myVector->end(); beg != end; beg++)
{
delete *beg;
}
myVector->clear();
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 vector
s.
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.
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.
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.
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.
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.
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.
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];
}
I decided to turn my comment into an answer (along with the other great answers here), so here it goes.
I would note again, that this case deals with inheritance of the object.
When you delete an array of Derived object, pointed by a Base pointer, as follows:
Base* pArr = new Derived[3];
delete [] pArr;
What the compiler does "under the hood" is to generate the following code:
//destruct the objects in *pArr in the inverse order
//in which they were constructed
for (int i = the number of elements in the array - 1; i >= 0; --i)
{
pArr[i].Base::~Base();
}
Now, when doing so, we get undefined behavior. Dealing with arrays is simply dealing with offsets so when this loop occurs, in each iteration of the loop the pointer of the array is incremented according to the size of Base --> and here is where things becomes "undefined". In the "simple" (yet less common) case where the Derived class does not add any members of its own, its size is as the size of Base --> so things might (I guess that not always) work well. But (!!) when you add at least one member to the Derived class, its size grows, causing the offset increment in each iteration to be wrong.
To illustrate this case I have create the following Base and Derived objects. Note that in the case that Derived does not contain the m_c member, the delete operation goes well (comment it out and see for yourself), YET once you add it, I got a segmentation fault (which is the undefined behavior).
#include <iostream>
using namespace std;
class Base
{
public:
Base(int a, int b)
: m_a(a)
, m_b(b)
{
cout << "Base::Base - setting m_a:" << m_a << " m_b:" << m_b << endl;
}
virtual ~Base()
{
cout << "Base::~Base" << endl;
}
protected:
int m_a;
int m_b;
};
class Derived : public Base
{
public:
Derived()
: Base(1, 2) , m_c(3)
{
}
virtual ~Derived()
{
cout << "Derived::Derived" << endl;
}
private:
int m_c;
};
int main(int argc, char** argv)
{
// create an array of Derived object and point them with a Base pointer
Base* pArr = new Derived [3];
// now go ahead and delete the array using the "usual" delete notation for an array
delete [] pArr;
return 0;
}