472,145 Members | 1,570 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,145 software developers and data experts.

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)
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));
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?


Expand|Select|Wrap|Line Numbers
  1.                  servObj.erase(itservObj);        
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 2134
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.                         }
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
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.