How to delete an object in a set

node ninja picture node ninja · Apr 30, 2011 · Viewed 22.4k times · Source

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.

Answer

Ben Stott picture Ben Stott · Apr 30, 2011

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