title: Alternatives to an Object Pool?
body: <p>I'm not quite sure that I need an object pool, yet it seems the most viable solution, but has some un-wanted cons associated with it. I am making a game, where entities are stored within an object pool. These entities are not allocated directly with new, instead a <code>std::deque</code> handles the memory for them. </p>
  
  <p>This is what my object pool more or less looks like:</p>
  
  <pre><code>struct Pool
  {  
      Pool()
          : _pool(DEFAULT_SIZE)
      {}
  
      Entity* create()
      {
          if(!_destroyedEntitiesIndicies.empty())
          {
              _nextIndex = _destroyedEntitiesIndicies.front();
              _destroyedEntitiesIndicies.pop();
          }
  
          Entity* entity = &amp;_pool[_nextIndex];
          entity-&gt;id = _nextIndex;
          return entity;
      }
  
      void destroy(Entity* x)
      {
          _destroyedEntitiesIndicies.emplace(x-&gt;id);
          x-&gt;id = 0;
      }
  
  private:
  
      std::deque&lt;Entity&gt; _pool;
      std::queue&lt;int&gt; _destroyedEntitiesIndicies;
      int _nextIndex = 0;
  };
  </code></pre>
  
  <p>If I destroy an entity, it's ID will be added to the <code>_destroyedEntitiesIndicies</code> queue, which will make it so that the ID will be re-used, and lastly it's ID will be set to 0. Now the only pitfall to this is, if I destroy an entity and then immediately create a new one, the Entity that was previously destroyed will be updated to be the same entity that was just created. </p>
  
  <p>i.e.</p>
  
  <pre><code>Entity* object1 = pool.create(); // create an object
  pool.destroy(object1); // destroy it
  
  Entity* object2 = pool.create(); // create another object
  // now object1 will be the same as object2
  
  std::cout &lt;&lt; (object1 == object2) &lt;&lt; '\n'; // this will print out 1
  </code></pre>
  
  <p>This doesn't seem right to me. How do I avoid this? Obviously the above will probably not happen (as I'll delay object destruction until the next frame). But this may cause some disturbance whilst saving entity states to a file, or something along those lines.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Let's say I did NULL entities to destroy them. What if I was able to get an Entity from the pool, or store a copy of a pointer to the actual entity? How would I NULL all the other duplicate entities when destroyed?</p>
  
  <p>i.e.</p>
  
  <pre><code>Pool pool;
  Entity* entity = pool.create();
  
  Entity* theSameEntity = pool.get(entity-&gt;getId());
  
  pool.destroy(entity);
  
  // now entity == nullptr, but theSameEntity still points to the original entity
  </code></pre>