ViewDesignEngine  3.1.0
高性能 CAD 计算几何引擎
memory_pool.h
浏览该文件的文档.
1 #pragma once
2 #include <cstddef>
3 #include <vector>
4 #include <new>
5 
6 namespace vde::foundation {
7 
29 template <typename T>
30 class MemoryPool {
31 public:
36  explicit MemoryPool(size_t chunk_size = 1024) : chunk_size_(chunk_size) {}
37 
41  ~MemoryPool() { for (auto* p : chunks_) ::operator delete(p); }
42 
54  T* allocate(size_t n = 1) {
55  if (free_list_ == nullptr) allocate_chunk();
56  T* p = static_cast<T*>(free_list_);
57  free_list_ = *reinterpret_cast<void**>(free_list_);
58  return p;
59  }
60 
68  void deallocate(T* p, size_t = 1) {
69  *reinterpret_cast<void**>(p) = free_list_;
70  free_list_ = p;
71  }
72 
73 private:
77  void allocate_chunk() {
78  void* chunk = ::operator new(chunk_size_ * sizeof(T));
79  chunks_.push_back(chunk);
80  char* base = static_cast<char*>(chunk);
81  for (size_t i = 0; i < chunk_size_; ++i) {
82  void* ptr = base + i * sizeof(T);
83  *reinterpret_cast<void**>(ptr) = free_list_;
84  free_list_ = ptr;
85  }
86  }
87 
88  size_t chunk_size_;
89  void* free_list_ = nullptr;
90  std::vector<void*> chunks_;
91 };
92 
93 } // namespace vde::foundation
固定块大小的内存池
Definition: memory_pool.h:30
MemoryPool(size_t chunk_size=1024)
构造内存池
Definition: memory_pool.h:36
~MemoryPool()
析构内存池,释放所有已分配的内存块
Definition: memory_pool.h:41
void deallocate(T *p, size_t=1)
将内存归还到池中
Definition: memory_pool.h:68
T * allocate(size_t n=1)
从池中分配 n 个 T 对象的内存
Definition: memory_pool.h:54
自适应双精度谓词后端(默认)
Definition: error_codes.h:4