codetoad.com
  ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || Forums || RAM 
Search Site:
Search Forums:
  Memory management: pointers in std:vector  jmch at 20:37 on Thursday, June 16, 2005
 

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!


  Re: Memory management: pointers in std:vector  Rashakil Fol at 01:10 on Tuesday, June 28, 2005
 

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.








CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums
//








Recent Forum Threads
•  Re: Problem with concatenation
•  how to genrates the crystal report by sending a id at runtime
•  help me
•  pls help me with this..
•  Re: Security - Code verify
•  Job @ EarlySail
•  Job @ EarlySail (perl)
•  IPC problem
•  Re: import contacts of msn/yahoo


Recent Articles
ASP GetTempName
Decode and Encode UTF-8
ASP GetFile
ASP FolderExists
ASP FileExists
ASP OpenTextFile
ASP FilesystemObject
ASP CreateFolder
ASP CreateTextFile
Javascript Get Selected Text


© Copyright codetoad.com 2001-2007