title: Correctly delete pointers in std::list allocated elsewhere
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/4260464/does-stdlistremove-method-call-destructor-of-each-removed-element">Does std::list::remove method call destructor of each removed element?</a>  </p>
  </blockquote>
  
  
  
  <p>I have a SpriteHandler class that allows the user to register a pointer to a Sprite object for drawing, all it does is access methods on the object. I wanted to write a safety catch that automatically deleted the memory associated with the pointers if the user forgot to do so by the end of the program (and it's less to worry about for the user too!) :</p>
  
  <pre class="lang-cpp prettyprint-override"> <code>
  
  //SpriteHandler.h
  class SpriteHandler {
  public:
  //...
      void RegisterObject(Sprite* object);
      bool IsRegistered(Sprite* object);
      void UnregisterObject(Sprite* object);
  private:
  //...
      static std::list&lt;Sprite*&gt;* _sprite = NULL;
  };
  
  //SpriteHandler.cpp
  std::list&lt;Sprite*&gt;* SpriteHandler::_sprites = NULL;
  
  
  void SpriteHandler::RegisterObject(Sprite* object) {
      if(object == NULL) return;
      if(_sprites == NULL) _sprites = new std::list&lt;Sprite*&gt;();
      _sprites-&gt;push_back(object);
      _sprites-&gt;sort(UDLessSprite);
  }
  
  bool SpriteHandler::IsRegistered(Sprite* object) {
      return std::binary_search(_sprites-&gt;begin(), _sprites->end(), object);
  }
  
  void SpriteHandler::UnregisterObject(Sprite* object) {
      if(object == NULL) return;
      if(IsRegistered(object) == false) return;
  
      _sprites-&gt;remove(object);
      if(_sprites-&gt;size() &lt;= 0) {
          if(_sprites) {
              _sprites-&gt;clear();
              delete _sprites;
              _sprites = NULL;
          }
          return;
      }
      _sprites-&gt;sort(UDLessSprite);
  }
  
  void SpriteHandler::Release() {
      if(_sprites) {
          std::list&lt;Sprite*&gt;::iterator _iter = _sprites->begin();
          while(_iter != _sprites->end()) {
              delete (*_iter);
              (*_iter) = NULL;
              ++_iter;
          }
          _sprites->clear();
          delete _sprites;
          _sprites = NULL;
      }
  }
  
  </code> </pre>
  
  <p>The issue I"m having is that after the first pointer is deleted the next iterator is pointing to an already freed object (memory location is 0xfeeefeee).</p>
  
  <p><strong>How would I correctly iterate through them, deleting each one?</strong></p>