Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an object in a set

In my C++ program, I create objects in one function using new. These objects are inserted into a set. When I want to remove objects from the set, I use an iterator in a for-loop. When I remove the object from the set, I still need to delete the object to free its memory, correct? I tried using delete, but then I get an error saying that the pointer being freed was not allocated. So how can this be done?

Here is the code where I create the object and then insert it into the set

set <myObject> myobjectlist;
myObject *myobject = new myObject;
myobjectlist.insert(*myobject);

In another function, I try to remove an object from the set, and free its memory:

    for (set<myObject>::iterator i = myobjectlist.begin(); i != myobjectlist.end(); i++)
if (i->myObjectID == myObjectID)
{
    myobjectlist.erase(*i);
    delete &i;
    break;
}

This works fine without the 'delete' part. I added it in because I thought that the memory from the object wasn't being freed.

like image 742
node ninja Avatar asked Apr 30 '11 01:04

node ninja


1 Answers

Assuming you're calling the set's erase() method, note that this will call the destructor of the object for you. After you erase() your object, it has already been deleted, and thus your second attempt to manually call delete will fail as the pointer is no longer allocated.

For reference, see this

like image 123
Ben Stott Avatar answered Sep 21 '22 05:09

Ben Stott