Files
ViewDesignEngine/include/vde/foundation/memory_pool.h
T

44 lines
1.1 KiB
C++

#pragma once
#include <cstddef>
#include <vector>
#include <new>
namespace vde::foundation {
template <typename T>
class MemoryPool {
public:
explicit MemoryPool(size_t chunk_size = 1024) : chunk_size_(chunk_size) {}
~MemoryPool() { for (auto* p : chunks_) ::operator delete(p); }
T* allocate(size_t n = 1) {
if (free_list_ == nullptr) allocate_chunk();
T* p = static_cast<T*>(free_list_);
free_list_ = *reinterpret_cast<void**>(free_list_);
return p;
}
void deallocate(T* p, size_t = 1) {
*reinterpret_cast<void**>(p) = free_list_;
free_list_ = p;
}
private:
void allocate_chunk() {
void* chunk = ::operator new(chunk_size_ * sizeof(T));
chunks_.push_back(chunk);
char* base = static_cast<char*>(chunk);
for (size_t i = 0; i < chunk_size_; ++i) {
void* ptr = base + i * sizeof(T);
*reinterpret_cast<void**>(ptr) = free_list_;
free_list_ = ptr;
}
}
size_t chunk_size_;
void* free_list_ = nullptr;
std::vector<void*> chunks_;
};
} // namespace vde::foundation