#pragma once #include #include #include namespace vde::foundation { template 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(free_list_); free_list_ = *reinterpret_cast(free_list_); return p; } void deallocate(T* p, size_t = 1) { *reinterpret_cast(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(chunk); for (size_t i = 0; i < chunk_size_; ++i) { void* ptr = base + i * sizeof(T); *reinterpret_cast(ptr) = free_list_; free_list_ = ptr; } } size_t chunk_size_; void* free_list_ = nullptr; std::vector chunks_; }; } // namespace vde::foundation