这应该是最简单的类了,只有一个 .h 文件,直接贴代码
template <class T>
class RenderCommandPool
{
public:
RenderCommandPool()
{
}
~RenderCommandPool()
{
// if( 0 != _usedPool.size())
// {
// CCLOG("All RenderCommand should not be used when Pool is released!");
// }
_freePool.clear();
for (typename std::list<T*>::iterator iter = _allocatedPoolBlocks.begin(); iter != _allocatedPoolBlocks.end(); ++iter)
{
delete[] *iter;
*iter = nullptr;
}
_allocatedPoolBlocks.clear();
}
T* generateCommand()
{
T* result = nullptr;
if(_freePool.empty())
{
AllocateCommands();
}
result = _freePool.front();
_freePool.pop_front();
//_usedPool.insert(result);
return result;
}
void pushBackCommand(T* ptr)
{
// if(_usedPool.find(ptr) == _usedPool.end())
// {
// CCLOG("push Back Wrong command!");
// return;
// }
_freePool.push_back(ptr);
//_usedPool.erase(ptr);
}
private:
void AllocateCommands()
{
static const int COMMANDS_ALLOCATE_BLOCK_SIZE = 32;
T* commands = new (std::nothrow) T[COMMANDS_ALLOCATE_BLOCK_SIZE];
_allocatedPoolBlocks.push_back(commands);
for(int index = 0; index < COMMANDS_ALLOCATE_BLOCK_SIZE; ++index)
{
_freePool.push_back(commands+index);
}
}
std::list<T*> _allocatedPoolBlocks;
std::list<T*> _freePool;
//std::set<T*> _usedPool;
};
这里使用了 模板和 (std::nothrow)来保证后面各种不同的RenderCommand的创建和销毁不会产生不希望看到的error跟警告 这里使用了两个list pool 来保证不会在对象使用时删除对象所在list的索引导致的迭代错误