The first thing to say: I do not really like C ++ 11, so there may be some kind of syntax error in the code that I wrote, but this logic matters.
If I understand your question, you just want to be able to add and remove elements from the container asynchronously without knowing their state. In this case, you can use std::map< std::unique_ptr< Elem >, bool > to process the state of the elements: true = alive, false = dead.
Memory class
fields:
std::vector< T * > m_toAdd , a vector with elements not yet added;std::map< std::unique_ptr< T >, bool > m_items , a map with each managed item and the bool flag
methods:
add() , which adds a new element to the vector m_toAdd ;del() , which marks the item to be deleted in m_items using its flag;refresh() , which removes dead elements and commits the m_toAdd ad live elements to m_items , then clears the vector
Class elem
fields:
MemoryManager & m_manager , a link to its memory manager;
methods:
Elem() , ctor, which calls m_manager::add() ;del() , which calls m_manager::del() .
Creature
When an Elem is created, it automatically adds itself to its memory manager, which adds it to its m_toAdd vector, and then when everything is updated, those Elem in this vector are passed to std::map paired with true boolean (originally designated as live) .
Delete
When deleting Elem it calls the manager's del() method, which simply marks it dead in its std::map , and then, when everything is updated, each Elem in the manager is marked dead as deleted, and the vector m_toAdd is cleared.
(I also recommend that you use std::enable_shared_from_this to handle ptr better, but you will need to use std::shared_ptr rather than std::unique_ptr , but that can't be so bad.)
My suggestion is something like:
template< class T > class MemoryManager { typedef std::unique_ptr< T > unique_t; typedef std::map< unique_t, bool > map_t; typedef std::pair< unique_t, bool > pair_t; typedef std::vector< T * > vector_t; public: void add(T * item) { m_toAdd.push_back(item); } void remove(T & item) { typename map_t::iterator it = m_items.find(item); if (it != m_items.end() )(* it).second = false; } void refresh() {
NOTE : the code is not verified and, of course, broken, the logic is important!