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.
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 delete
d, and thus your second attempt to manually call delete will fail as the pointer is no longer allocated.
For reference, see this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With