MemoryPoolAllocator, Stack: lazily allocate Allocators

In order to make the constructors more efficient, especially
in the context of C++11 move semantics, the (dynamic) allocations
in MemoryPoolAllocator and Stack should be performed lazily.

Move the allocations to the first use of the allocator in both
classes.
This commit is contained in:
Philipp A. Hartmann 2014-10-30 18:40:58 +01:00
parent d0c283254b
commit e8f5d9f8ef
2 changed files with 6 additions and 7 deletions

View File

@ -104,9 +104,6 @@ public:
MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
{
if (!baseAllocator_)
ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator());
AddChunk(chunk_capacity_);
}
//! Constructor with user-supplied buffer.
@ -216,6 +213,8 @@ private:
/*! \param capacity Capacity of the chunk in bytes.
*/
void AddChunk(size_t capacity) {
if (!baseAllocator_)
ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator());
ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(sizeof(ChunkHeader) + capacity));
chunk->capacity = capacity;
chunk->size = 0;

View File

@ -37,8 +37,6 @@ public:
// Do it lazily when first Push() -> Expand() -> Resize().
Stack(Allocator* allocator, size_t stackCapacity) : allocator_(allocator), ownAllocator_(0), stack_(0), stackTop_(0), stackEnd_(0), initialCapacity_(stackCapacity) {
RAPIDJSON_ASSERT(stackCapacity > 0);
if (!allocator_)
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
}
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
@ -140,9 +138,11 @@ private:
void Expand(size_t count) {
// Only expand the capacity if the current stack exists. Otherwise just create a stack with initial capacity.
size_t newCapacity;
if (stack_ == 0)
if (stack_ == 0) {
if (!allocator_)
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
newCapacity = initialCapacity_;
else {
} else {
newCapacity = GetCapacity();
newCapacity += (newCapacity + 1) / 2;
}