Properly destroying pointers in an std::map

As far as your sample code goes, you need to do this inside the loop:

delete itr->second;

The map has two elements and you need to delete the second. In your case, itr->first is a std::string and itr->second is a Texture*.

If you need to delete a particular entry, you could do something like this:

std::map<std::string, Texture*>::iterator itr = textureMap.find("some/path.png");
if (itr != textureMap.end())
{
    // found it - delete it
    delete itr->second;
    textureMap.erase(itr);
}

You have to make sure that the entry exists in the map otherwise you may get an exception when trying to delete the texture pointer.

An alternative might be to use std::shared_ptr instead of a raw pointer, then you could use a simpler syntax for removing an item from the map and let the std::shared_ptr handle the deletion of the underlying object when appropriate. That way, you can use erase() with a key argument, like so:

// map using shared_ptr
std::map<std::string, std::shared_ptr<Texture>> textureMap;

// ... delete an entry ...
textureMap.erase("some/path.png");

That will do two things:

  • Remove the entry from the map, if it exists
  • If there are no other references to the Texture*, the object will be deleted

In order to use std::shared_ptr you’ll either need a recent C++11 compiler, or Boost.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)