diff --git a/dl/dl.h b/dl/dl.h index 94b5440c..6a196cab 100644 --- a/dl/dl.h +++ b/dl/dl.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include diff --git a/dl/memory/dl_memory_reuse.h b/dl/memory/dl_memory_reuse.h new file mode 100644 index 00000000..90e11a1d --- /dev/null +++ b/dl/memory/dl_memory_reuse.h @@ -0,0 +1,169 @@ +/** +* @file dl_memory_reuse.h +* @brief 复用内存 +* + +* @version 1.1 +* @author lveyou +* @date 24-08-05 +*/ +#pragma once + +#include +#include +#include + +namespace dl::Memory +{ + +//! new内存复用 +template +class MemoryReuse +{ +public: + MemoryReuse() + {} + + template + T* New(Args&& ...args) + { + void* p; + if (_list.empty())//没有空闲内存则新建 + { + p = malloc(sizeof(T)); + } + else + { + p = _list.back(); + _list.pop_back(); + } + return new (p) T(args...); + } + + void Delete(T* p) + {//调用析构函数,并放入list + ((T*)p)->~T(); + _list.push_back(p); + } + ~MemoryReuse() + { + for (auto& iter : _list) + free(iter); + } +private: + std::vector _list; +}; + +template +class ReuseCheck +{ +public: + ReuseCheck() + {} + + template + T* New(Args&& ...args) + { + void* p = nullptr; + if (_list.empty()) + { + if (_countCur + 1 > _countMax) + return nullptr; + p = malloc(sizeof(T)); + if (!p) + return nullptr; + } + else + { + p = _list.back(); + _list.pop_back(); + } + T* pp = new (p) T(args...); + + { + assert(_newList.find(pp) == _newList.end()); + _newList[pp] = 1; + ++_countCur; + } + + return pp; + } + + bool Delete(T* p) + { + { + if (!p) + return true; + auto it = _newList.find(p); + if (it == _newList.end()) + { + assert(0 && "Not Find Memory Object"); + delete p; + return false; + } + _newList.erase(it); + --_countCur; + } + + ((T*)p)->~T(); + _list.push_back(p); + return true; + } + + bool Find(T* p) + { + auto it = _newList.find(p); + return it != _newList.end(); + } + + void Clear2Num(size_t num) + { + if (num >= _list.size()) + return; + auto iter0 = _list.begin() + num; + for (auto iter1 = iter0; iter1 != _list.end(); ++iter1) + { + free(*iter1); + } + _list.erase(iter0, _list.end()); + } + + void Reserve(size_t n) + { + _list.reserve(n); + } + + void SetCountMax(int n) + { + _countMax = n; + } + + size_t GetCountMax() + { + return _list.size() + _countCur; + } + + size_t GetCount() + { + return _countCur; + } + + size_t GetCountFree() + { + return _list.size(); + } + + ~ReuseCheck() + { + for (auto& iter : _list) + free(iter); + assert(_countCur == 0); + } + +private: + std::vector _list; + size_t _countCur = 0; + size_t _countMax = 64000; + std::unordered_map _newList; +}; +} \ No newline at end of file