|
I'm making a small game where I have a class Cell (which is a graphical square in the game) and I save all these Cells in a vector: std::vector<Cell*>
Now, when I want to deallocate the memory I have a loop that looks like this:
-------------------
for (int i = 0; i < NO_OF_CELLS; i++) {
delete v.at(i);
}
v.clear();
-------------------
My questions are:
1. Is this correct?
2. Which destructor is called? Do I need a destructor in class Cell? If yes, why is that?
3. Is there a problem if one of the elements in the vector are 0? I.e. v[5] = 0. It seems to be the case for me and I don't see why..
Thanks!
|
|
|
This looks correct. The delete operator takes a pointer as its argument, and if you've got a vector of pointers to cell objects allocated with 'new', then operating delete on each of the pointers will call the destructor of each Cell object.
You only need to write your own destructor for the Cell object if that object has its own allocated memory to delete. (E.g. if the constructor for a Cell uses the new operator with its own data structures, you'd want to have the destructor deleting any objects that are lying around.) If objects of the Cell class do not dynamically allocate memory, then you do not need to write your own destructor.
If one of the elements is NULL, which you've called 0, that is okay. Running (delete 0) is legal -- it is a non-operation.
|
|
|
|
|
|
|
// |