Delete object that is stored in Vector

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thelamb
    New Member
    • Aug 2008
    • 2

    #1

    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:
    [code=c]
    servObj.push_ba ck(new CGame(serversh, game_id)); (1)
    [/code]

    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:
    [code=c]
    delete &(servObj.at(0) );
    [/code]
    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:

    [code=c]
    servObj.erase(i tservObj);
    [/code]

    here itservObj is a vector::iterato r. 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
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    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.

    Comment

    • thelamb
      New Member
      • Aug 2008
      • 2

      #3
      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:

      Code:
       for( itservObj=l_servObj.begin(); itservObj != l_servObj.end(); itservObj++)
                      {
                              if( (**itservObj).whoareyou(serversh) == true )
                              {
                                      delete (*itservObj);
                                      l_servObj.erase(itservObj);
                              }
      Dont know why this didnt work the first try, but thanks for your help anyway :)

      Comment

      Working...