469,133 Members | 1,007 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,133 developers. It's quick & easy.

Delete object that is stored in Vector

Hello all,

I have a question about deleting objects(the objects are stored in a vector)

I Fill the vector as following:
Expand|Select|Wrap|Line Numbers
  1.         servObj.push_back(new CGame(serversh, game_id)); (1)
  2.  
Since I am calling new, I need to call delete somewhere else in the program.

If I try to delete the first object that was stored in servObj like this:
Expand|Select|Wrap|Line Numbers
  1.                 delete &(servObj.at(0));
  2.  
And try to erase the first element after that I get segmentation fault(makes sense).

Now my question is, if I just erase the first element, will it cleanly destroy the object that was stored in the first element?

So:

Expand|Select|Wrap|Line Numbers
  1.                  servObj.erase(itservObj);        
  2.  
here itservObj is a vector::iterator. Will this deallocate the memory properly?

I havnt been coding in C++ for that long(read: never had to bother with memory management) so I would appreciate anyone pushing me in the right direction here.

Thanks in advance
Aug 3 '08 #1
2 2013
weaknessforcats
9,208 Expert Mod 8TB
Have you run this in the debugger to see of the CGame destructor is called?

What you have stored in the vector is a pointer to a heap object. Erasing the pointer in the vector does not delete the object.

The vector::at returns a reference to the pointer. Therefore, you should be deleting servObj.at(0), which is your pointer.
Aug 3 '08 #2
Ok I just tried again, and for some reason it works now where it didnt work before(I guess I missed something in my first try).

For anyone who cares:

Expand|Select|Wrap|Line Numbers
  1.  for( itservObj=l_servObj.begin(); itservObj != l_servObj.end(); itservObj++)
  2.                 {
  3.                         if( (**itservObj).whoareyou(serversh) == true )
  4.                         {
  5.                                 delete (*itservObj);
  6.                                 l_servObj.erase(itservObj);
  7.                         }
  8.  
  9.  
Dont know why this didnt work the first try, but thanks for your help anyway :)
Aug 3 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

8 posts views Thread by Maximus | last post: by
16 posts views Thread by cppaddict | last post: by
11 posts views Thread by DamonChong | last post: by
35 posts views Thread by Jon Slaughter | last post: by
19 posts views Thread by Daniel Pitts | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.