30 #ifndef PT_POOLALLOCATOR_H
31 #define PT_POOLALLOCATOR_H
34 #include <Pt/Allocator.h>
36 #include <Pt/NonCopyable.h>
71 typedef std::size_t Record;
72 static const Record RecordSize =
sizeof(Record);
73 static const Record InvalidIndex = std::size_t(-1);
79 std::size_t firstFreeIndex;
81 std::size_t availUnits;
86 Block(std::size_t unitSize_, std::size_t numUnits)
88 , firstFreeIndex(InvalidIndex)
90 , availUnits(numUnits)
96 {
return availUnits == 0; }
99 {
return availUnits == maxUnits; }
105 firstFreeIndex = InvalidIndex;
110 assert(availUnits > 0);
112 if( firstFreeIndex != InvalidIndex )
114 assert(firstFreeIndex < endIndex);
115 Record* retval = block + firstFreeIndex;
116 firstFreeIndex = *retval;
123 block =
new Record[maxUnits*unitSize];
127 Record* retval = block + endIndex;
128 endIndex += unitSize;
130 assert(endIndex <= maxUnits*unitSize);
135 void deallocate(Record* ptr)
137 assert(availUnits <= maxUnits);
139 *ptr = firstFreeIndex;
140 firstFreeIndex = ptr - block;
141 assert( ptr >= block );
142 assert( ptr <= (block + endIndex) );
149 MemoryPool(std::size_t elemSize, std::size_t maxPageSize = 8192);
157 if( _freelist.empty() )
159 _freelist.push_back( _blocks.size() );
160 _blocks.push_back( Block(_recordsPerUnit, _maxUnits) );
163 const std::size_t index = _freelist.back();
164 Block& block = _blocks[index];
166 Record* retval = block.allocate();
171 _freelist.pop_back();
182 Record* unitPtr =
reinterpret_cast<Record*
>(ptr);
185 const std::size_t blockIndex = *unitPtr;
186 Block& block = _blocks[blockIndex];
189 _freelist.push_back(blockIndex);
191 block.deallocate(unitPtr);
194 if( block.isEmpty() && blockIndex > 0 )
199 std::vector<Block> _blocks;
200 std::vector<std::size_t> _freelist;
203 std::size_t _recordsPerUnit;
204 std::size_t _maxUnits;
250 PoolAllocator(std::size_t maxSize, std::size_t align = 16, std::size_t maxBlock = 8192);
258 if (size > _maxObjectSize || 0 == size)
260 return ::operator
new( size );
263 const std::size_t index = (size-1) / _objectAlignSize;
265 assert (index < _pools.size() );
273 if (size > _maxObjectSize || NULL == p)
275 ::operator
delete(p);
281 const std::size_t index = (size-1) / _objectAlignSize;
282 assert (index < _pools.size() );
294 std::vector<MemoryPool*> _pools;
297 const std::size_t _maxObjectSize;
300 const std::size_t _objectAlignSize;
void * allocate(std::size_t size)
Allocates size bytes of memory.
Definition: PoolAllocator.h:256
Protects derived classes from being copied.
Definition: NonCopyable.h:54
void * allocate()
Allocates memory.
Definition: PoolAllocator.h:155
void deallocate(void *ptr)
deallocates memory.
Definition: PoolAllocator.h:177
Pool based allocator.
Definition: PoolAllocator.h:245
Memory pool for objects of the same size.
Definition: PoolAllocator.h:69
Allocator interface.
Definition: Allocator.h:81
void deallocate(void *p, std::size_t size)
Deallocates memory of size bytes.
Definition: PoolAllocator.h:271