I am implementing a naive memory pool, and there are two classes in my implementation.
The FixedMemoryPool<T> and MemoryBlock<T>
The FixedMemoryPool provides interfaces to users like newElement, and it manage memory through MemoryBlock.
And it's clear that none of the user should have accessibility to MemoryBlock, it's lifecycle is completely managed by FixedMemoryPool. For each MemoryBlock<T>, it can only be created by FixedMemoryPool<T>.
Here's my implementation.
template
<typename T>
class FixedMemoryPool;
template<typename T>
class MemoryBlock
{
friend class FixedMemoryPool<T>;
using blockPtr = unique_ptr<MemoryBlock<T>>;
struct _ConstructorTag { explicit _ConstructorTag() = default; };
public:
MemoryBlock(size_t blockSize, _ConstructorTag)
:data(reinterpret_cast<T*>(operator new(sizeof(T) * blockSize))), allocatedCounter(0), next(nullptr)
{
}
~MemoryBlock()
{
for (size_t i = 0; i != allocatedCounter; i++) {
(data + i) -> ~T();
}
operator delete(data);
}
private:
T* data;
size_t allocatedCounter;
blockPtr next;
template
<typename... Args>
T* construct(Args&&... args)
{
//...
}
MemoryBlock(const MemoryBlock&) = delete;
MemoryBlock& operator=(const MemoryBlock&) = delete;
};
template
<typename T>
class FixedMemoryPool
{
public:
using valueType = T;
FixedMemoryPool(size_t blockSize = 64)
:blockSize(blockSize), head(make_unique<MemoryBlock<T>>(blockSize, MemoryBlock<T>::_ConstructorTag{}))
{
}
FixedMemoryPool(const FixedMemoryPool&) = delete;
FixedMemoryPool& operator=(const FixedMemoryPool&) = delete;
FixedMemoryPool(FixedMemoryPool&& pool) = delete;
FixedMemoryPool& operator=(FixedMemoryPool&&) = delete;
template
<typename... Args>
T* newElement(Args&&... args)
{
//...
}
~FixedMemoryPool() = default;
private:
void expand()
{
// ...
}
size_t blockSize;
unique_ptr<MemoryBlock<T>> head;
};
Thanks for this link. I know how to enabling make_unique with private ctor. However, i want to know if there is any better way to fulfill my desire.
Also, is my usage to operator new and operator delete right?
Aucun commentaire:
Enregistrer un commentaire