C++ Disposing Textures Recently, I've asked in a code review if my code was causing any pointer related issues. They mentioned that I had problems with my dispose method. Basically, I'm disposing textures from a texture map, by cleaning the texture at the ID given to the method. So I would like to ask you if now, I'm disposing correctly my texture, and if there's a better way to do it.

void TextureManager::freeTexture(std::string id){

    std::map&lt;std::string, SDL_Texture*&gt;::iterator it = m_textureMap.find(id);

    std::cout &lt;&lt; "Disposing texture : [ID==" &lt;&lt; id &lt;&lt; "] [MemoryAdress==" &lt;&lt; it-&gt;second &lt;&lt; "] : \n";

    if (it == m_textureMap.end())
    {
        LOGERROR("ERROR : Invalid ID : cannot dispose texture");
        return;
    }

    SDL_DestroyTexture(it-&gt;second);
    std::cout &lt;&lt; "--&gt; Destroyed !";

    m_textureMap.erase(id);
    std::cout &lt;&lt; " --&gt; Erased from TextureMap !\n\n";
}
Yes, I think it is fine. erase() will get rid of the &lt;key,value&gt; pair indexed by the id.

A tiny optimization here would be calling erase() with the iterator it instead of the id string. This should avoid a second lookup, since the iterator already contains the relevant information map need to remove the item. You can see here that erase() operates on keys or iterators.

Also, pass your id string by const reference, since the method does not need a copy of the string. E.g.:

void TextureManager::freeTexture(const std::string &amp; id) { /* ... */ }
                                 ^^^^^             ^


This is a very long and error prone line:


std::map&lt;std::string, SDL_Texture*&gt;::iterator



You should typedef the map type or use auto if targeting C++11.

Typedefing map somewhere:

// In the header file somewhere...
typedef std::map&lt;std::string, SDL_Texture*&gt; TextureMap;

// Then it is a little simpler to use:
TextureMap::iterator it = map.find(...);


Or just use auto if you can:

auto it = map.find(...);